Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent class name? [duplicate]

Tags:

python

oop

class A(object):     def get_class(self):         return self.__class__  class B(A):     def __init__(self):         A.__init__(self)  b = B() print b.get_class() 

This code will print <class '__main__.B'>.

How can I get the class name where the method has been defined (namely A)?

like image 482
Francis.TM Avatar asked Apr 10 '12 15:04

Francis.TM


People also ask

How do you call parent class method with same name?

Answer. When you define a method in the child class with the same name as a parent class method, it will override the method. Then, when you call the method on an instance of the child class, it will run the method defined in that child class.

What does super () __ Init__ do?

Understanding Python super() with __init__() methods It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. The super() function allows us to avoid using the base class name explicitly.

What is __ bases __ in Python?

Python provides a __bases__ attribute on each class that can be used to obtain a list of classes the given class inherits. The __bases__ property of the class contains a list of all the base classes that the given class inherits. The above output shows that the Human class has object as a base class.


1 Answers

From the documentation: https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy

Class objects have a __name__ attribute. It might cleaner to introspect the base class(es) through the __bases__ attr of the derived class (if the code is to live in the derived class for example).

>>> class Base(object): ...     pass ... >>> class Derived(Base): ...     def print_base(self): ...         for base in self.__class__.__bases__: ...             print base.__name__ ... >>> foo = Derived() >>> foo.print_base() Base 
like image 160
Jeremy Brown Avatar answered Oct 30 '22 20:10

Jeremy Brown