【发布时间】:2018-07-06 01:19:33
【问题描述】:
我试图用继承的类解决方案回答this question here,但是当我在我的 IDE 上测试它时,我的解决方案并没有像我预期的那样出现。我做了一些搜索,但找不到答案。
这是我提出的解决方案:
class PseudoInteger(int):
def __init__(self, x, base=10, hid_obj=""):
self.hidden_object = hid_obj
super(int, PseudoInteger).__init__(x, base)
pseudo_integer = PseudoInteger('5', hid_obj="Hello World")
print(5 + pseudo_integer) # Expects "10"
print(pseudo_integer == 5) # Expects "True"
print(pseudo_integer.hidden_object) # Expects "Hello World!"
据我了解,这在理论上应该可行。但是当我运行它时,这就是我得到的:
pseudo_integer = PseudoInteger('5', hid_obj="Hello World") TypeError: 'hid_obj' is an invalid keyword argument for this function
我尝试在启动实例时添加base=10,但仍然失败:
pseudo_integer = PseudoInteger('5', base=10, hid_obj="Hello World") TypeError: int() takes at most 2 arguments (3 given)
我以为我搞砸了,所以我编写了自己的类并继承了它,但它工作正常:
class foo(object):
def __init__(self, x, y=10):
pass
class bar(foo):
def __init__(self, x, y=10, z=""):
self.z = z
super(foo, bar).__init__(x, y)
foobar = bar(1, z="hello")
print(foobar.z)
# Output
# hello
我的问题是 - 为什么我不能继承内置的 int 类并添加一个额外的参数,但是当它从我的 foo 类继承时它工作正常?是限制还是我搞砸了?
除了@Melvin 建议 super() 在 Python 3 中不需要 args 之外,我在我的自定义类上进行了尝试,它可以工作。但是在内置的继承类中,我得到了另一个意想不到的行为:
super().__init__(x, base) TypeError: object.__init__() takes no parameters
内置插件很奇怪。
【问题讨论】:
-
这是 python 2 还是 3?如果是 3,你的 super() 中不需要 arg。
-
@Melvin 我在 Python 3.6.3 上运行。我可以在我的自定义类中不带 arg 的
super()但在继承的int类中不能。我得到另一个意外行为:TypeError: object.__init__() takes no parameters。这是……另一个问题? -
好吧,
TypeError: object.__init__() takes no parameters只是意味着int在其__init__中不接受任何输入参数,我之前实际上并没有从int继承,给我一些时间试试出来:) -
您传递给
__init__的参数首先传递给__new__,并且由于您的子类没有覆盖父类的__new__,因此签名不匹配。这是一个小的工作示例:repl.it/repls/ClearCourageousAlbertosaurus -
@Mevin 这不是问题。他们可以将自定义参数添加到他们的子类中。
标签: python class inheritance built-in