我想使用超类来调用类的父方法,同时使用不同的类。
Class AI():
...
for i in self.initial_computer_group:
if i.rect.x == current_coords[0] and i.rect. y== current_coords[1]:
i.move(coords_to_move[0], coords_to_move[1])当我想要父类的原始方法时,i.move()从继承的类调用一个方法。
self.initial_computer_group包含一个与AI类完全无关的对象列表。
我知道我需要以某种方式获得我引用的当前对象的类名,但是我不知道在super()中使用什么作为第二个参数,因为我不能使用self,因为它与AI无关。
那么,当我在一个完全不同的类中时,如何使用super()呢?
注意:,我想调用父方法,因为它加速了一切。我设计继承的方法只是为了确保人类在这盘棋中不会违反规则。
编辑:我通过将继承的方法的名称更改为其他方法找到了一个解决方案,但是我想知道是否还有一种特殊的方法来调用super()来解决这个问题
发布于 2014-08-04 12:52:43
听起来您想要调用特定类的方法,不管继承图是什么样子(特别是,即使该方法碰巧被重写了两次)。在这种情况下,您不需要super。相反,直接调用类的方法。例如,假设您想要的版本在Foo类中:
Foo.move(i, coords_to_move[0], coords_to_move[1])发布于 2014-08-04 12:36:48
由于注释中的代码很难读懂,下面是一个简单的示例:
class BaseClass():
def func(self):
print("Here in BaseClass.")
class InheritedClass(BaseClass):
def func(self):
print("Here in InheritedClass.")
def func(instance):
super(InheritedClass, instance).func()在使用中:
>>> func(InheritedClass())
Here in BaseClass.但这显然降低了代码的灵活性(因为instance参数必须是InheritedClass实例),通常应该避免使用。
发布于 2014-08-04 15:09:32
给定某些继承层次结构:
class Super: # descends from object
def func():
return 'Super calling'
class Base(Super):
def func():
return 'Base calling'
class Sub(Base):
def func():
return 'Sub calling' 您可以使用resolution hierarchy属性获得__mro__:
>>> s=Sub()
>>> s.__class__.__mro__
(<class '__main__.Sub'>, <class '__main__.Base'>, <class '__main__.Super'>, <class 'object'>)然后,您可以按索引从这些索引中选择:
>>> s.__class__.__mro__[-2]
<class '__main__.Super'>
>>> s.__class__.__mro__[-2].func()
Super calling您可以通过与__name__属性进行匹配来获得特定的名称:
def by_name(inst, tgt):
for i, c in enumerate(inst.__class__.__mro__):
if c.__name__==tgt:
return i
return -1 然后,如果要调用不相关类的父类,只需在子类的实例上使用这些方法之一,并使用感兴趣的方法。
当然,最简单的答案是,如果您知道您想要的类和方法,只需直接调用它:
>>> Super.func()
Super calling
>>> Base.func()
Base calling 如果您需要在几个级别上(或一个未知的级别)来查找该方法,Python将为您完成以下操作:
class Super:
def func():
return 'Super calling'
class Base(Super):
pass
class Sub(Base):
pass
>>> Sub.func()
Super callinghttps://stackoverflow.com/questions/25118472
复制相似问题