Python中删除Frame.__init__吗?

2024-04-25 01:38:48 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码,我想删除框架。\u init\u部分:

class Black(Frame):
    def __init__(self, parent, width, height, ):
        Frame.__init__(self,parent, bg='black')
        self.width = width
        self.height = height

手动删除时,会出现错误:

AttributeError: 'Black' object has no attribute 'tk'

我认为这将是一个小而愚蠢的错误。有人能帮我吗?你知道吗


Tags: 代码self框架initdef错误手动width
2条回答

你的Black类是从Frame类派生的,你的__init__()重写基类的。你知道吗

您需要Frame.__init__(self,parent, bg='black')来正确初始化对象。你知道吗

看一下docs并阅读关于继承的更多说明

如果你不想成为一个Frame,而是想拥有一个,你不应该继承它。只需将一个存储为属性:

class Black(object): # note no inheritance from Frame
    def __init__(self, parent, width, height, )
        # instance of calling its __init__ with self,
        # we just construct a Frame and store it
        self.frame = Frame(parent, bg='black')
        self.width = width
        self.height = height

现在,要调用Frame方法,需要执行self.frame.spam(),而不是self.spam()等等。你知道吗


如果你想假装成一个Frame而不是一个,只拥有一个,你可以通过将每个Frame方法和属性委托给self.frame(显式地,或者通过__getattr__)来实现;如果你真的需要,你甚至可以假装isinstance。但这是一个高级用例,您必须学习一些复杂的东西才能使其顺利工作,所以希望这不是您想要的。你知道吗

相关问题 更多 >