How do i call an outside function from this class ? Show
user 5,1497 gold badges46 silver badges70 bronze badges asked Mar 7, 2015 at 7:48
1 To call
the class method, you can create an instance of the class and then call an attribute of that instance (the
Alternatively you can call it this way:
Sidenote: I made a few changes to your code. answered Mar 7, 2015 at 8:20
useruser 5,1497 gold badges46 silver badges70 bronze badges 4
Problem Statement: How to define a method outside of class definition in Python? Example: # Given Class class Demo: # Given Method def foo(self): x = 10 return x Can we create
IntroductionWe all know Python is an object-oriented programming language, and in Python, everything is an object including properties and methods. In Python, the class is like an object’s constructor for creating the objects. Thus, the variables can be defined inside the class, outside the class, and inside the methods in Python. The variables defined outside the class can be accessed by any method or class by just writing the variable name. So, in this article, we are going to learn how to define a method outside of the class definition. What are Methods in Python? As Python is an object-oriented programming language, it has objects that consist of properties. The attributes define the properties of these objects, and the behavior is defined using methods. Methods are reusable pieces of code called at any point in the program and are defined inside the class. Every method is associated with the class and can be invoked on the instances of that class. For example, we can consider a class named ‘
Here’s how you can assign the values: class Student: def __init__(self, name, id, rank): self.name = name self.id = id self.rank = rank def run(self): print(f'{self.name} is a cross country champion!') def jump(self): print(f'{self.name} with the following ID: {self.id} is a high jumper!') def swim(self): print(f'{self.name} secured rank {self.rank} in swimming.') stud1 = Student('Finxter', 1020, 1) stud1.run() stud1.jump() stud1.swim() Output:
The above example demonstrated the traditional way of adding functionality (methods) to a Python class. Here, the methods were defined inside the class body. Now, let’s say that you want to define a method outside the class body. How will you do so? Let’s dive into the different approaches to unearth the answers to this question. Define The Method Outside and Use Inside Class BodyThe idea here is to define the method outside the class and then use it inside the class body, as shown below. Example 1: # Defining the method outside the class def foo(self): print("Method foo executed") x = 10 print("Value of x = ", x) # Using the method inside the class body class Demo: my_method = foo You can also define a class first and then add a method or function to it from outside its body, as shown below. Example 2: # Define the class class Demo: pass # Define the method outside the class def foo(self): print("Method foo executed ") # Pass the method to the class Demo.method1 = foo Caution: We can even define the functions, methods, and classes in different modules if we want to. However, it is advisable to use example 1 rather than example 2 (defining the class in one module, then importing it into another module and further adding methods to it dynamically) because the class objects may behave differently depending on whether the module has been imported or not. There’s another way to define the function outside of a class and then further add it. But there is a difference in assigning the function to the instance object or the class. Look at the following example to understand the subtle difference: class Demo1(object): def __init__(self, bar): self.func = 'Finxter' Demo1.funcbar = bar class Demo2(object): def __init__(self, bar): self.func = 'Finxter' self.funcbar = bar def bar(self): return 'Welcome' + self.func Explanation: Let’s understand what’s happening here.
Using InheritanceYou can even use the methods of a class in another class. In the following example we have a class class Helper(object): # Subtraction function def subs(self, a, b): return a - b # Addition function def add(self, a, b): return a + b # Multiplication function def mul(self, a, b): return a * b # Division function def div(self, a, b): return a / b # Given class class Demo(Helper): def __init__(self): Helper.__init__(self) print("The addition of numbers is", self.add(10, 5)) print("Subtraction of numbers is", self.subs(60, 15)) print("Multiplication of numbers is", self.mul(5, 9)) print("The division of numbers is", self.div(100, 50)) # Main method if __name__ == '__main__': obj = Demo() Output:
Related Read: Inheritance in Python ConclusionTo sum things up, it is absolutely possible to have functions outside classes in Python. If you want to gather a group of functions in one box then you can simply put them together in the same module. Further, you can nest modules within packages. It is recommended that you should use classes when you have to create a new datatype and don’t just use it to group functions together. That’s it for this discussion and I hope it helped you. Please stay tuned and subscribe for more interesting articles and discussions in the future. Happy learning! Article by Shubham Sayon and Rashi Agarwal I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking. You can contact me @:
UpWork How do you call an outside function from a class in Python?To call the class method, you can create an instance of the class and then call an attribute of that instance (the test_def method).
Can you call a function outside a class?Yes you can definitely have functions outside of a class.
How do you use an outside class function?C++ class and functions: Outside the class definition
Functions should be declared inside the class to bound it to the class and indicate it as it's member but they can be defined outside of the class. To define a function outside of a class, scope resolution operator :: is used.
Can I call a function in a class Python?To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.
|