Python There are some magical ways to do it , They are always surrounded by double underscores , They are object-oriented Of Python Everything . They are special ways to add magic to your classes , If your object implements ( heavy load ) A magic method , Then this method will be automatically used in special cases Python The call .
This method defines the behavior when a user attempts to access a nonexistent property .
self Refers to the object itself ,item Is a string , Represents the name of the attribute to be accessed .
The default is None, The return value is automatically returned to the object that triggered it .
Example
class MyTest:
def __getattr__(self, item):
return 18
sample = MyTest()
print(sample.age)
# Use '.' This method is triggered when the operator accesses the object
print(sample.__dict__)
When __getattribute__ and __getattr__ Simultaneous existence , Will execute first __getattribute__ Method , If the method can normally return a value , that __getattr__ Method will not be executed . If the method does not return a value normally ( There was an exception (AttributeError) Or attribute does not exist ), be __getattr__ The method will be in __getattribute__ Then it's executed .__getattr__()
Functions are special functions . It only works if the attribute cannot be in the instance's __dict__ Or its class , Or when found in the ancestor class , It's called . Programmers mainly use __getattr__() To achieve class flexibility , Or use it to do some operations . In most cases , What is needed is __getattr__().
Example :
class Count(object):
def __init__(self, min, max):
self.min = min
self.max = max
self.current = None
def __getattribute__(self, item):
print(type(item), item)
if item.startswith('cur'):
raise AttributeError
return object.__getattribute__(self, item)
obj1 = Count(1, 10)
print(obj1.min)
print(obj1.max)
print(obj1.current)