Python __getattr__和__setattr__本领

Python __getattr__和__setattr__本领

__getattr__是类在挪用属性时,即使没有该属性会机动挪用的邪术本领

__setattr__是类在树立属性(包括已有属性从新窜改属性值)时会机动挪用的邪术本领

话不多说,径直上例子,如有题目烦恼留言给小编。小编用的是python3.6.9

class Person(object):

def __init__(self, name):

# 挪用__setattr__本领

self.name = name

# 没有对应的属性时,会挪用__getattr__

def __getattr__(self, item):

print(item,"-"*10)

# 树立属性时会挪用__setattr__本领,囊括__init__树立属性时

# 树立好后就不会再挪用了

def __setattr__(self, key, value):

print(key,value,"*"*10)

# 这一条龙意旨宏大,不许用self.key = value

# 由于如许的话仍旧会挪用__setattr__,产生死轮回

self.__dict__[key] = value

a = Person("大锤") # 输入:name 大锤 ********** (初始化挪用了__init__)

print(a.name) # 输入:大锤 (不挪用__setattr__,因不是树立属性)

a.name = 666 # 输入:name 666 ********** (挪用了__setattr__)

a.age # 输入:age ---------- (挪用了__getattr__)

a.zsd = 100 # 输入:zsd 100 ********** (挪用了__setattr__)

分享到 :
相关推荐

Leave a Reply

Your email address will not be published. Required fields are marked *