【问题标题】:How do I call a static method within a nested class?如何在嵌套类中调用静态方法?
【发布时间】:2019-01-27 23:15:49
【问题描述】:

我有两个班,一个是Parent,另一个是Child

Child 中,我有两个静态函数foo()bar()。 在foo(),我想打电话给bar()

但是由于Child是嵌套的,我不能用常规方式调用它。

Class Parent:

    Class Child:

        @staticmethod
        def foo():
            Child.bar() #Doesn't work

        @staticmethod
        def bar():
             pass

【问题讨论】:

    标签: python-3.x class nested static-methods


    【解决方案1】:

    有两种主要方法可以实现您的目标:

    1. 像这样引用ParentChild 类:

      class Parent:
      
          class Child:
      
              @staticmethod
              def foo():
                  Parent.Child.bar()
      
              @staticmethod
              def bar():
                   pass
      
    2. 使用由解释器 based on lexical scoping 创建的隐式 __class__ 单元格:

      class Parent:
      
          class Child:
      
              @staticmethod
              def foo():
                  __class__.bar()
      
              @staticmethod
              def bar():
                  pass
      

    这两种方法在 Python 3.x 中都是完全可行的。

    有 3 个注意事项:

    1. 静态方法的过度使用有时是设计缺陷的一个指标,在这种情况下,外部独立函数会是更好的选择。

    2. 这些方法都不适用于继承。如果继承自 Parent.ChildParent.Child.bar() 将引用同一个旧类的方法,而 __class__ 将显示相同的原始 Parent.Child 类,因为使用了词法范围。

    3. 如果使用某些类装饰器,第一种方法将导致无限递归。使用__class__ 可确保您引用真正的原始类,并且可能有助于消除该问题。

    【讨论】:

    • class 看起来很棒!谢谢。 class vs Parent.Child 有什么限制吗?
    • @Pathfinder 没有我能想到的限制或差异。如果有人愿意加入并补充,我将不胜感激。
    • 实际上,如果使用类装饰器,__class__ 可能会更好。它可以帮助避免无限递归。我稍后会添加完整的解释。
    【解决方案2】:

    您误将Child 类的命名空间放在Parent 类中,并从Parent 类扩展Child 类。

    您可以像这样从Parent 扩展Child 类:

    class Parent:
        a = 1
    
    class Child(Parent):
        pass
    
    >>> Child.a
    1
    

    与静态方法相同。

    【讨论】:

    • Parent 成为Child 的“子类”似乎有点不必要的混乱...
    • @ShadowRanger 我同意——我把顺序搞混了。现在更新。
    • 他不想扩展,OP显然希望嵌套一个类,因此虽然是真的,但答案有点无关紧要。
    • @Bharel 鉴于他说“但由于 Child 是嵌套的,我不能使用传统方式调用它。”然后他的代码说Child.bar(),我解释为想要扩展
    • 可能是,我不完全确定。嵌套在封装方面确实有它的优势。我可能不喜欢它,但话又说回来,我只是在这里回答 OP :-)
    【解决方案3】:

    在嵌套类中调用静态函数时,还必须引用父类。

    Class Parent:
    
        Class Child:
    
            @staticmethod
            def foo():
                 Parent.Child.bar()
    
            @staticmethod
            def bar():
                pass
    

    【讨论】:

      猜你喜欢
      • 2016-01-05
      • 1970-01-01
      • 2021-04-09
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多