Skip to main content
 首页 » 编程设计

python之如何使用类范围而不是类方法范围初始化/定义子类

2025年05月04日8mate10pro

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

我可以编写这段代码,但每次调用 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,确实允许引用定义中的类。

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

此外,我相信您的设计已损坏。如果 Child 与 Parent 严格相关,那么您应该使用继承,在这种情况下您只需执行 self.getParentName(),无需任何花哨的东西,或者您可以使用委派。

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