class A:
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
B() # output: hello
Run Code Online (Sandbox Code Playgroud)
在我使用超级构造函数的所有其他语言中隐式调用.如何在Python中调用它?我希望,super(self)但这不起作用.
我正在尝试用Python制作一个面向对象的基于文本的游戏,并尝试实现我的第一个属性和装饰器.使用"Python 3面向对象编程"一书中的第5章,我尝试使用所讨论的示例和概念来获取以下代码,以便在实例化时设置Game-object的'current_room'属性:
class Room(object):
''' An area of the game's map.'''
def __init__(self):
print("Accessing the Room __init__ method.")
class FirstRoom(Room):
''' Just some room.'''
def __init__(self):
print("Accessing the FirstRoom __init__ method.")
super.__init__()
class SecondRoom(Room):
''' Just some other room.'''
def __init__(self):
print("Accessing the SecondRoom __init__ method.")
super.__init__()
class Game(object):
''' Creates a new game.'''
current_room = None # Class-level definition of this property.
def __init__(self):
print("Created a new Game object.")
self.current_room = FirstRoom()
@property
def current_room(self):
''' Returns …Run Code Online (Sandbox Code Playgroud) 这是我试图编写的代码:
class A(object):
def bind_foo(self):
old_foo = self.foo
def new_foo():
old_foo()
#super().foo()
super(self.__class__,self).foo()
self.foo = new_foo
def __init__(self):
print("A __init__")
def foo(self):
print("A foo")
class B(A):
def __init__(self):
print("B __init__")
super().__init__()
def foo(self):
print("B foo")
super().foo()
class C(A):
def __init__(self):
print("C __init__")
super().__init__()
super().bind_foo()
def foo(self):
print("C foo")
b = B()
b.foo()
c = C()
c.foo()
Run Code Online (Sandbox Code Playgroud)
B类和A类是预期的行为,也就是说,当我打电话时b.foo(),它a.foo()也会调用super().C类是试图模仿孩子B和父A行为,但这次我不想明确地super().foo()放在子类中,但我仍然想要父类foo()调用.它按预期工作.
然而,我不太明白的是A.bind_foo,我必须使用super(self.__class__,self).foo()而不是super().foo.super().foo给了一个
"SystemError: super(): no arguments". …Run Code Online (Sandbox Code Playgroud) 假设我有以下父类和子类:
class A(object):
def __init__(self, *args, **kwargs):
self.a = kwargs.get('a', 'default_A')
self.b = kwargs.get('b', 'default_B')
class B(A):
a = "override_A"
def __init__(self, *args, **kwargs):
super(B, self).__init__(**kwargs)
b = B()
print b.b # this is "default_B", as expected
print b.a # I expected this to be "override_A"
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?我试图通过像这样的答案来理解继承是如何工作的,但是没有找到描述这个特定要求的东西.