我已经定义了一个处理通用内容的基类,以及更具体的子类,它们接受的内容(对象类型)。但是,在调用父类中定义的函数时,使用的是父变量而不是子变量。如何让 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_types
在 set
中。
将所有出现的 __accepted_types
更改为 accepted_types
,它将正常工作。
p.s 如果您确实在使用 Python 3,basestring
不存在,请使用 str
。
关于python - 在父函数中使用子函数覆盖的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43741035/