gpt4 book ai didi

python - 在父函数中使用子函数覆盖的值

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:44 24 4
gpt4 key购买 nike

我已经定义了一个处理通用内容的基类,以及更具体的子类,它们接受的内容(对象类型)。但是,在调用父类中定义的函数时,使用的是父变量而不是子变量。如何让 Python 在父函数中使用子变量?

示例代码:

class BaseField(object):
__accepted_types = (object,)

def __init__(self, description=""):
self.content = None
self.description = description

def set(self, content):
if isinstance(content, self.__accepted_types):
print(type(content), self.__accepted_types)
print(type(self))
self.__set(content)
else:
raise ValueError("wrong type")

def __set(self, content):
pass

class StringField(BaseField):
__accepted_types = (basestring,)

def __init__(self, description=""):
super().__init__(description)
print(self.__accepted_types)

if __name__ == '__main__':
x = StringField("a test field")
x.set(3)

我希望这段代码引发一个ValueError(我试图将一个int传递给一个只接受str的类),但是我得到以下结果:

(<class 'str'>,)
<class 'int'> (<class 'object'>,) <class '__main__.StringField'>

请注意,该函数正确返回它在 "StringField" 中,但使用 "BaseField" 值作为 __accepted_types。如果我将 __accepted_types 声明为实例变量,行为是相同的。

最佳答案

您正成为名称修改的牺牲品;名称在类主体中被破坏,self.__accepted_types 被转换为 _BaseField__accepted_typesset 中。

将所有出现的 __accepted_types 更改为 accepted_types,它将正常工作。

p.s 如果您确实在使用 Python 3,basestring 不存在,请使用 str

关于python - 在父函数中使用子函数覆盖的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43741035/

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