繁体   English   中英

为什么我的 python class 不能从另一个 class 继承?

[英]Why won't my python class inherit from another class?

class Media_Work(object):

  def __init__(self):

    _id: int = 0
    _IdDict: {} 
    _titleDict: {}

class Poem(Media_Work):

  def __init__(self, id, title, author, content, age, mtype, verbs):

    super().__init__()
    self.id = id
    self.title = title
    self.author = author
    self.content = content
    self.age = age
    self.mtype = mtype
    self.verbs = verbs

    Poem._IdDict.update({id: self})

我的错误信息:

AttributeError:“诗”object 没有属性“_IdDict”

如果我将底线更改为:

self._IdDict.update({id:self})

新的错误信息:

AttributeError:类型 object 'Poem' 没有属性 '_IdDict'

如前所述,您的预期dict _IdDict确实是一种类型提示参阅 ShadowRanger 的评论)!

将属性设置为class 变量(可能是您的意图)或在__init__()中分配属性


Class 变量
引用将在 class 声明中创建,并由 class 的所有实例共享
在这种情况下不需要调用super()来初始化

class Media_Work():

    _id     = 0
    _IdDict = {}

属性
引用将在 class init时创建,并且对 class 的每个实例都是唯一的

class Media_Work():

    def __init__(self):
        self._id     = 0
        self._IdDict = {} 

它正在继承,但您尚未定义_IdDict class 属性。 _IdDict: {}类型提示,而不是定义,它是__init__中的本地名称,而不是 class 属性。

这是如何修复它的示例。 您可能需要对其进行定制以满足您的需求:

class Media_Work:
    _IdDict = {}

class Poem(Media_Work):
    def __init__(self, _id):
        Poem._IdDict.update({_id: self})

示例用法:

>>> p = Poem(17)
>>> Poem._IdDict
{17: <__main__.Poem object at 0x7f13689a3ba8>}
>>> Media_Work._IdDict
{17: <__main__.Poem object at 0x7f13689a3ba8>}

顺便说一句,不要使用id作为变量名,因为它是内置的。

[我以前的这个答案版本没有]....你有两个问题。 首先是您未能为 _IdDict 分配值,因此未创建它。 其次,您在错误的 scope 中定义了它。 如果您想创建一个 Class 属性,您需要在 __init__ 方法中将其称为 Media_Work._IdDict ,或者您需要在方法之外定义它。 如:

class Media_Work(object):

    _id: int = 0
    _IdDict: {} = {}
    _titleDict: {} = {}

    def __init__(self):
        Media_Work._id = 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM