繁体   English   中英

python中的父__unicode__

[英]Parent __unicode__ in python

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

但是,如果您修改基类以使其成为新样式类 ,则可以使用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()

您可以通过以下几种方式引用父方法:

class Dog(Animal):
      def __unicode__(self):
           return 'this %s is a dog' % Animal.__unicode__(self)

class Dog(Animal):
     def __unicode__(self):
           return 'this %s is a dog' % super(Dog, self).__unicode__()

注意:为了使用super,父类必须是新的样式类。 如果与问题中定义的旧样式类一起使用,则第二种方法将失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM