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

标签 python python-3.x class

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

相关文章:

python-3.x - python socket(TCP)程序没有结束

ubuntu - 如何在 Ubuntu 15.04 中安装新的请求库

python - 将 C 函数转换为 Python3 形式?

php - 扩展 PHP 类

python - 结合两个机器学习模型的结果

python - DeprecationWarning : Non-string object detected for the array ordering. 请改为传入 'C' 、 'F' 、 'A' 或 'K'

python - 无法使用我的抓取工具中的方法生成的链接

java - 如何让 FillInTheBlank 打印问题(继承)

python - 使用 python 模块 impyla 连接到 Kerberized hadoop 集群

javascript - JavaScript 中 Var 的 bool 值