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

Python magic method (12):__ getattr __ (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

This method defines the behavior when a user attempts to access a nonexistent property .

Parameters

self Refers to the object itself ,item Is a string , Represents the name of the attribute to be accessed .

Return value

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)


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