__new__ Allocate memory for a new object and send it to the __init__ function (you don’t interact with this one)
__init__ Receive a new object from the __new__ function as a “self” parameter
classMyInt:
'''Docstring for MyInt'''def__init__(self, val):
self.value = val
def__add__(self, other):
return MyInt(self.value + other)
def__repr__(self):
returnf'MyInt({self.value})'def__str__(self):
returnf'{self.value}'defsquare(self):
"Return the square of the value"return MyInt(self.value**2)
MyInt
__main__.MyInt
num = MyInt(42)
num +5# calls .__add__ the .__repr__ methods
MyInt(47)
print(num)
42
num
MyInt(42)
# In Jupyter use ``??`` to see source codeMyInt.square??
Example:
classEmployee:
'Common base class for all employees' empCount =0def__init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount +=1def__del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"defdisplayCount(self):
print "Total Employee %d"% Employee.empCount
defdisplayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
The getattr(obj, name[, default]) − to access the attribute of object.
The hasattr(obj,name) − to check if an attribute exists or not.
The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.
The delattr(obj, name) − to delete an attribute.
Common dunder variables:
__dict__ − Dictionary containing the class’s namespace.
__doc__ − Class documentation string or none, if undefined.
__name__ − Class name.
__module__ − Module name in which the class is defined. This attribute is “main” in interactive mode.
__bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.