__str__
class Student (object): def __init__ (self, name): = name def__str__(self): return' Student Object (name:%s)' % self.name __repr__ = __str__
#作用: Internal information can be printed directly
Print (Student ('Michael')) Student object (Name:michael)
__getattr__
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:
classStudent (object):def __init__(self): Self.name='Michael' def __getattr__(self, attr):ifattr=='score': return99
>>> s =Student ()
>>> S.name
'Michael'
>>> S.score
about
#返回函数也是完全可以的:
Class Student (object): def__getattr__(self, attr): if attr=='age': returnLambda: 25
Just call the method to change to:
>>> S.age ()
25
Any call s.abc
will be returned None
, because the default return that we define is __getattr__
None
. To allow class to respond to only a few specific properties, we are going to throw the error according to the Convention AttributeError
:
class Student (object): def __getattr__ (self, attr): if attr=='age': returnLambda: 25 raise attributeerror ('\ ' student\ ' object has no attribute \ '%s\ ' % attr
This actually allows all the properties and method invocations of a class to be dynamically processed, without any special means.
Action Example:
With completely dynamic __getattr__
, we can write a chain call:
classChain (object):def __init__(Self, path="'): Self._path=Pathdef __getattr__(self, path):returnChain ('%s/%s'%(Self._path, path))def __str__(self):returnSelf._path__repr__=__str__
>>> Chain (). Status.user.timeline. List
'/status/user/timeline/list '
In this way, regardless of the API changes, the SDK can be based on the URL to achieve a full dynamic call, and not with the increase of the API to change!
__call__
In any class, you can simply __call__()
invoke the instance by defining a method.
class Student (object): def __init__ (self, name): = name def__call__(self): print('My Name is%s. ' % self.name)
The method is called as follows:
>>> s = Student (' Michael ')
# Self parameter do not pass in
Is Michael.
Python3 Learning Notes Custom class