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 .
Defines the behavior of an instance object when its properties are accessed ( Whether the attribute exists or not , another : Accessing properties by class name does not call this method )
self Represents the object itself ,item Is a string , Represents the attribute name
The default is None, The return value is automatically returned to the object that triggered it , Usually by return super().getattribute(item) return item The value of the property .
class MyTest:
def __init__(self, age):
self.age = age
def __getattribute__(self, item):
return super().__getattribute__(item)
sample = MyTest(18)
print(sample.age)
class Tree(object):
def __init__(self, name):
self.name = name
self.cate = "plant"
def __getattribute__(self, obj):
print(" ha-ha ")
return object.__getattribute__(self, obj)
aa = Tree(" The tree ")
print(aa.name)
Execution results :
ha-ha
The tree
Why is this result ?
__getattribute__ Is a property access interceptor , When the properties of this class are accessed , Will call the class automatically __getattribute__ Method .
In the above code , When the instance object is called aa Of name Attribute , Will not print directly , But the name The value of is passed as an argument __getattribute__ In the method ( Parameters obj You can call it anything ), After a series of operations , And then name The value of the return .Python As long as inheritance is defined in object Class , There are attribute interceptors by default , It's just that no operation is performed after interception , I'm going straight back .
You can rewrite it yourself __getattribute__ Methods to realize related functions , For example, view permission 、 Print log Log etc. . The following code :
class Tree(object):
def __init__(self, name):
self.name = name
self.cate = "plant"
def __getattribute__(self, *args, **kwargs):
if args[0] == "name":
print("log The tree ")
return "this is The tree "
else:
return object.__getattribute__(self, *args, **kwargs)
aa = Tree(" The tree ")
print(aa.name)
Execution results :
log The tree
this is The tree
plant