假设我有一个名为 Animal 的类和一个名为 Dog 的子类。如何从 Dog 类访问 Animal 的 unicode 定义?
class Animal:
def __unicode__(self):
return 'animal'
class Dog(Animal):
def __unicode__(self):
return 'this %s is a dog' % (I want to get the Animal's __unicode__ here)
最佳答案
由于您在 Python 2 中实现旧式类,您只能通过限定名称访问基类的方法:
class Animal:
def __unicode__(self):
return 'animal'
class Dog(Animal):
def __unicode__(self):
return 'this %s is a dog' % Animal.__unicode__(self)
但是,如果您修改基类,使其变为 new-style class , 那么你可以使用 super() :
class Animal(object):
def __unicode__(self):
return 'animal'
class Dog(Animal):
def __unicode__(self):
return 'this %s is a dog' % super(Dog, self).__unicode__()
请注意,所有类都是 Python 3 中的新式类,因此在运行该版本时始终可以使用 super()
。
关于python - python 中的父 __unicode__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14933493/