简体   繁体   English

在python的未绑定方法中继承和访问父类

[英]Inheritance and accessing parent class in unbound method in python

I have this class with an unbound method and a static class inside: 我有一个带有未绑定方法和静态类的类:

class ClassA():
    class Foo():
        pass

    def getFoo():
        return ???.Foo

Now, if I inherit a ClassB from ClassA how do I get ClassB.getFoo() to return ClassB.Foo without explicitly implementing ClassB.getFoo()? 现在,如果我从ClassA继承了ClassB,如何在不显式实现ClassB.getFoo()的情况下让ClassB.getFoo()返回ClassB.Foo? Returning super().Foo doesn't work, writing ClassA.Foo doesn't work either obviously. 返回super().Foo不起作用,编写ClassA.Foo显然也不起作用。

Your getFoo should be a classmethod: 您的getFoo应该是一个类方法:

class ClassA():
    class Foo():
        pass

    @classmethod
    def getFoo(cls):
        return cls.Foo

Class methods are passed their class as their first argument, similar to how instance methods are passed the instance as the first argument. 类方法通过其类作为其第一个参数传递,类似于实例方法将实例作为第一个参数传递。 When you subclass ClassA, the proper class is passed. 当您将ClassA子类化时,将传递适当的类。

Just to add my own thoughts on this: In addition to @Ned Batchelder's answer, you can use static methods to achieve a similar goal. 只是对此添加自己的想法:除了@Ned Batchelder的答案,您可以使用静态方法来实现类似的目标。

class ClassA():
    class Foo():
       def fooTest(self):
         print("Hello from {}!".format(self.__name__))

  @staticmethod
  def getFoo():
    return ClassA.Foo

class ClassB(ClassA):
    pass

And test with: 并测试:

>>> Foo = ClassB.getFoo()
>>> foo = Foo()
>>> foo.fooTest()
Hello from Foo!

This to me demonstrates the beauty of the python language - there are usually multiple ways of solving the same problem... 这向我展示了python语言的美丽-通常有多种方法可以解决同一问题...

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

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