【问题标题】:(Iron)Python inheritance constructor issue(铁)Python继承构造函数问题
【发布时间】:2012-06-14 21:30:10
【问题描述】:

所以我试图创建一个 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

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

【问题讨论】:

  • 我对 IronPython 不是很熟悉,但 __init__() 似乎应该没问题。也许整个追溯会有所帮助。
  • 唯一的事情是回溯没有告诉我调用构造函数之后发生了什么,所以没有有用的信息。
  • 嗯,所以这似乎是 Python 2.7(最新版本的 IronPython 使用)的错误,它不允许这样做。
  • Python 2.7 绝对允许这样做。除非父类有什么奇怪的地方。但是您的意思是调用 super(TableColumn, self) 而不是 super(TableColumn, self).__init__()?
  • 另外,TypeError 是由 TableColumn 的 init 方法引发的,还是从其他地方引发的?

标签: .net python inheritance constructor ironpython


【解决方案1】:

您实际上不想在从 .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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    相关资源
    最近更新 更多