If I have two classes, and one of them has a function that I want to use in my other class, what do I use so that I don't have to rewrite my function?
Call method from another class in a different class in Python. we can call the method of another class by using their class name and function with dot operator. then we can call method_A from class B by following way: class A: method_A(self): {} class B: method_B(self): A.
To class a method of another class, we need to have the object of that class. Here, we have a class Student that has a method getName() . We access this method from the second class SimpleTesting by using the object of the Student class.
In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems.
Instance methods are built functions into the class definition of an object and require an instance of that class to be called. To call the method, you need to qualify function with self. . For example, in a class that contains functions first() and second(), first() can call second().
There are two options:
Example:
class A(object): def a1(self): """ This is an instance method. """ print "Hello from an instance of A" @classmethod def a2(cls): """ This a classmethod. """ print "Hello from class A" class B(object): def b1(self): print A().a1() # => prints 'Hello from an instance of A' print A.a2() # => 'Hello from class A'
Or use inheritance, if appropriate:
class A(object): def a1(self): print "Hello from Superclass" class B(A): pass B().a1() # => prints 'Hello from Superclass'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With