gpt4 book ai didi

python - 在 __setattr__ 中访问对象的属性

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:59 26 4
gpt4 key购买 nike

今天 Python 咬了我。我试图在其 __setattr__ 实现中访问对象的属性 - 我不知道如何访问。到目前为止,这是我尝试过的:

class Test1(object):
def __init__(self):
self.blub = 'hi1'

def __setattr__(self, name, value):
print self.blub

class Test2(object):
def __init__(self):
self.blub = 'hi2'

def __setattr__(self, name, value):
print object.__getattr__(self, 'blub')

class Test3(object):
def __init__(self):
self.blub = 'hi3'

def __setattr__(self, name, value):
print object.__getattribute__(self, 'blub')

class Test4(object):
def __init__(self):
self.blub = 'hi4'

def __setattr__(self, name, value):
print self.__getattr__('blub')

class Test5(object):
def __init__(self):
self.blub = 'hi5'

def __setattr__(self, name, value):
print self.__getattribute__('blub')

class Test6(object):
def __init__(self):
self.blub = 'hi6'

def __setattr__(self, name, value):
print self.__dict__['blub']

测试:

try:
TestX().bip = 'bap'
except Exception as ex:
print ex

X16

输出:

'Test1' object has no attribute 'blub'
type object 'object' has no attribute '__getattr__'
'Test3' object has no attribute 'blub'
'Test4' object has no attribute '__getattr__'
'Test5' object has no attribute 'blub'
'blub'

有什么建议吗?

最佳答案

因为在 __init__ 中,它试图设置调用 __setattr__blub;它没有设置任何内容,只是尝试访问(和打印)blub,但没有找到任何内容并引发错误。检查这个:

>>> class Test2(object):
def __init__(self):
print "__init__ called"
self.blub = 'hi2'
print "blub was set"

def __setattr__(self, name, value):
print "__setattr__ called"
print self.blub


>>> Test2()
__init__ called
__setattr__ called

Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
Test2()
File "<pyshell#9>", line 4, in __init__
self.blub = 'hi2'
File "<pyshell#9>", line 9, in __setattr__
print self.blub
AttributeError: 'Test2' object has no attribute 'blub'
>>>

关于python - 在 __setattr__ 中访问对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18204227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com