(铁)Python继承构造函数issu

2024-09-30 16:37:41 发布

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

所以我尝试创建DataGridViewColumn的一个子类,它既有一个无参数构造函数,又有一个接受一个参数的构造函数,它需要DataGridViewCell类型。这是我的课:

class TableColumn(DataGridViewColumn):
    def __init__(self, string):
        super(TableColumn, self)
        self.Text = string
        self.CellTemplate = DataGridViewTextBoxCell()
        self.ReadOnly = True

每当我试图将字符串作为参数传入时:

^{pr2}$

它总是给我这个:

TypeError: expected DataGridViewCell, got str

所以它似乎总是将“string”传递给超类的单参数构造函数。我尝试过用super(TableColumn,self)替换super(TableColumn,self)。__init__(),以明确地确定我想调用无参数构造函数,但似乎没有任何效果。在


Tags: textself类型参数stringinitdef子类
1条回答
网友
1楼 · 发布于 2024-09-30 16:37:41

实际上,当从.NET类派生时,you need to implement ^{} instead实际上并不想实现__init__。在

class TableColumn(DataGridViewColumn):
    def __new__(cls, string):
        DataGridViewColumn.__new__(cls)
        self.Text = string
        self.CellTemplate = DataGridViewTextBoxCell()
        self.ReadOnly = True

基本上,.NET基类的构造函数需要在Python子类__init__之前调用(但在__new__之后),这就是为什么您调用了错误的DataGridViewColumn构造函数。在

相关问题 更多 >