如何使用类作用域而不是类方法作用域初始化/定义子类



如何使用使用类范围初始化子类?如何将父抽象类范围传递给子类?

我可以编写这段代码,但是每次调用getChild时,我都会创建一个类,但希望避免:

class Parent(object): # abstract class!
  @staticmethod
  def getParentName():
    raise NotImplementedError()
  @classmethod
  def getChild(cls): # solid class
    class Child(object):
      @staticmethod
      def getChildName():
        return 'Child of ' + cls.getParentName()
    return Child
class SomeParent(Parent):
  @staticmethod
  def getParentName():
    return 'Solid Parent'
print SomeParent.getChild().getChildName() # == 'Child of Solid Parent'

如何将上面的代码转换为在父作用域中定义子类(考虑到父类是抽象的,所以我们不能使用 Parent2.getParentName(),因为它会被覆盖?

class Parent2(object): # abstract class!
  @staticmethod
  def getParentName()
    raise NotImplementedError()
  class Child2(object): # solid class
    # what code here to do the same like Child???
    pass
class SomeParent2(Parent): # final class
  @staticmethod
  def getParentName()
    return 'Solid Parent2'
SomeParent2.getChildClass().getChildName() # == 'Child of Solid Parent2'
除了没有建设性的帮助或提示之外,

任何帮助或提示都将受到欢迎。

你不能

Python 没有声明。它具有类定义。定义 Parent2 类时,将执行缩进代码。这意味着在父类存在之前创建其中定义的任何内部类。因此,不可能Child2知道类范围内的Parent2。请注意,这与其他语言非常不同,例如允许引用定义中的类的 Ruby。

另请注意,您的两个示例执行了两件非常不同的事情。如果将类定义放在每次调用该方法时都会创建一个类的方法中,而在类范围内这样做意味着只会创建一个类在父范围内。

我也相信你的设计坏了。如果ChildParent严格相关,那么您应该使用继承,在这种情况下,您只需执行self.getParentName(),没有任何花哨的东西,或者您可以使用委派。

如果你真的想做这件事,那么你必须在定义父类后以某种方式"修复"类。为此,您可以使用类装饰器,或者简单地将代码显式放在父类之后。

最新更新