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