gpt4 book ai didi

.net - (Iron)Python继承构造函数问题

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:01 26 4
gpt4 key购买 nike

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

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

每当我尝试传入一个字符串作为参数时,如下所示:

foo = TableColumn('Name')

它总是给我这个:

TypeError: expected DataGridViewCell, got str

所以看起来它总是将“string”传递给父类(super class)的单参数构造函数。我尝试将 super(TableColumn, self) 替换为 super(TableColumn,self).__init__() ,以明确确定我想调用 no-参数构造函数,但似乎没有任何作用。

最佳答案

当从 .NET 类派生时,您实际上不想实现 __init__you need to implement __new__ instead

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

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

关于.net - (Iron)Python继承构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11041639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com