Dunder Methods
Last updated
__init__This method is implicitly called by the class and sets up all the attributes for us
__bases__You have to remember that the __bases__ property holds the information about the immediate super class of the class. It is not aware of any other hierarchy. Also, it contains the super classes in a tuple and NOT a list.
class A:
pass
class B(A):
pass
class C(B):
pass
print(C.__bases__)- Output: (<class '__main__.B'>, )
__dict__Every object in python has an attribute which is denoted by __dict__. And this object contains all attributes defined FOR the object. Since var has not been defined with the self keyword, it is a CLASS variable and will be shared by ALL objects of class A. Due to this it will not appear in the 'dict' property of object a. 'var' will be present in the 'dict' property of class A. So output for above code will be an empty dictionary.
__repr__Unambiguas representation of the object - Used for debugging and meant for devs
Is good to implement this to return a string used to recreate the object:
once you print the object, it should return how to re-create the object
__str__Readable version of the object
is meant to be as a display for the end user
Should return the username and email address when printed
This outputs the same result as the above print statements
__add__This is used for arihmetic
The above code is basically the same thing
In the second print statement is how python calls it
Strings use their special __add__ method
This method will output: ab
__add__ dunder method you are able to add employee salaries for example:__len__By using len(object) you are calling a dunder method in the backgroud:
Last updated
class A:
var = 100
def __init__(self):
pass
a = A()
print(a.__dict__)print(emp_1)print(emp_1)