Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python using methods from other classes

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?

like image 263
James Avatar asked May 09 '10 09:05

James


People also ask

How do I use a method from another class in Python?

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.

Can you call methods from other classes?

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.

Can a method be called from another method in a class Python?

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.

How do you call a method in another method in Python?

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().


1 Answers

There are two options:

  • instanciate an object in your class, then call the desired method on it
  • use @classmethod to turn a function into a class method

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' 
like image 66
miku Avatar answered Oct 04 '22 09:10

miku