__str__
__repr__
__iter__
__next__
__getitem__
__getattr__
Normally, when we call a method or property of a class, it will be an error if it does not exist. For example Student
, define a class:
class Student (object): def __init__ (self): ' Michael '
Call name
Properties, no problem, but call a nonexistent score
property, there is a problem:
>>> s = Student ()print(s.name) Michaelprint(s.score) Traceback ( Most recent call last): 'Student'score '
The error message clearly tells us that the attribute was not found score
.
To avoid this error, in addition to adding a score
property, Python has another mechanism, which is to write a __getattr__()
method that dynamically returns an attribute. Modify the following:
class Student (object): def __init__ = " michael " def __getattr__ " Span style= "COLOR: #000000" > (self, attr): if attr==" score " : return "
When a non-existent property is called, for example score
, the Python interpreter attempts to invoke __getattr__(self, ‘score‘)
the property, so that we have a chance to return score
the value:
>>> s = Student ()>>> s.name'Michael'>>> S.score99
The return function is also perfectly possible:
class Student (object): def __getattr__ (self, attr): if attr=='age': returnLambda: 25
Just call the method to change to:
>>> s.age ()25
Note that an existing attribute is called only if no attribute is found, __getattr__
for example name
, it is not located in __getattr__
.
Python: Custom-made classes