python - python 中的父 __unicode__

标签 python inheritance

假设我有一个名为 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/

相关文章:

c++ - 在 C++ 中传递参数时继承类之间的类型转换

python - 如何在 python 中为 AES 生成强一次性 session key

模板参数中的 C++ 继承

java - java中为什么限制在内部类中声明静态成员变量?

Java 对象扩展

java - 理解继承和覆盖

python - 运行train.py文件时训练期间发生StopIteration错误

python - 函数列表 Python

php - 如何从网页调用python脚本

python - `conda uninstall` 和 `pip uninstall` 是否也删除了依赖项但仅删除了其他包未使用的依赖项?