程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python magic method (11):__ getattribute __ (self, item) method

編輯:Python

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 .

function

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 )

Parameters

self Represents the object itself ,item Is a string , Represents the attribute name

Return value

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 .

Example

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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved