Init is called when an object is instantiated by calling the class. Here we define an initializer which has default arguments and test its behaviour.
class myDund:"""Test class for dunder methods. Other dunder methods are added as the explanation goes"""def__init__(self, number: int=0# an integer number , text: str="nothing"): # a stringself.number, self.text = number, texttest1 = myDund()print(test1.number, test1.text)test2 = myDund(42,"something")print(test2.number, test2.text)print(test1)test2
One thing to improve is the presentation of my object when printed or returned to the prompt. Str is called when print or str(built-in func, not obj method) is called on the object
def myStr(self: myDund):"""Implementation of __str__()"""returnf"({self.number}: {self.text})"myDund.__str__= myStrprint(test1)str(test1), test1
Hash generates a per run random number (if not int/float) for an object.
Hash calls __hash__() on an object if defined and truncates if representation is of higher bit width than host machine.
print(hash(1))print(f"Hash for class {myDund.__name__}: {hash(myDund)}")print(f"Hash for object {test2}, id {id(test2)}: {hash(test2)}")print(f"Hash for object {test3}, id {id(test3)}: {hash(test3)}")
1
Hash for class myDund: 172505833084
Hash for object (42: something), id 2760109428944: 172506839309
Hash for object (42: something), id 2760109431584: 172506839474
The __hash__() method can then be overwritten for custom behaviour.
myDund.__hash__=lambdaself: hash(self.text)print(f"Hash for class {myDund.__name__}: {hash(myDund)}")print(f"Hash for object {test2}, id {id(test2)}: {hash(test2)}")print(f"Hash for object {test3}, id {id(test3)}: {hash(test3)}")
Hash for class myDund: 172505833084
Hash for object (42: something), id 2760109428944: 6151054915300685838
Hash for object (42: something), id 2760109431584: 6151054915300685838
“Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.”
myDund.__dir__=lambdaself: "this is inside"print(dir(test1)) # returns as a sorted listmyDund.__dir__=lambdaself: ["this", "is", "inside"]print(dir(test1)) # already a list, just sorts