2013-04-25 66 views
0

什麼是錯誤使用以下代碼?Python:使用靜態方法的嵌套類失敗

class A: 
    def A_M(self): pass 
    class B: 
     @staticmethod 
     def C(): super(B).A_M() 

錯誤(Python的2.7.3):

>>> a = A() 
>>> a.B.C() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "..x.py", line 36, in C 
    def C(): super(B).A_M() 
NameError: global name 'B' is not defined 

編輯
解決方案很簡單,因爲這:

class A: 
    def A_M(self): pass 
    class B: 
     @staticmethod 
     def C(): A().A_M()     #use of A() instead of supper, etc. 

重要事項,有一個問題與此解決方案。如果您更改超級名稱(即A),則必須更新其本身的所有用途,如A :))。

+0

你爲什麼想要嵌套類?幾乎沒有理由在Python中使用它。 – 2013-04-25 08:52:17

+0

_「如果你改變超類的名字(即A),那麼你將不得不更新所有使用內部自身作爲A」_ - **這不是什麼_super class_意味着** – Eric 2013-04-25 21:02:30

回答

3
class A(object): 
    def foo(self): 
     print('foo') 

    @staticmethod 
    def bar(): 
     print('bar') 

    class B(object): 
     @staticmethod 
     def bar(obj): 
      # A.foo is not staticmethod, you can't use A.foo(), 
      # you need an instance. 
      # You also can't use super here to get A, 
      # because B is not subclass of A. 
      obj.foo() 
      A.foo(obj) # the same as obj.foo() 

      # A.bar is static, you can use it without an object. 
      A.bar() 

class B(A): 
    def foo(self): 
     # Again, B.foo shouldn't be a staticmethod, because A.foo isn't. 
     super(B, self).foo() 

    @staticmethod 
    def bar(): 
     # You have to use super(type, type) if you don't have an instance. 
     super(B, B).bar() 


a, b = A(), B() 

a.B.bar(a) 
b.foo() 
B.bar() 

super(B, B)詳見this

+0

解決辦法是:'A類: DEF A_M(個體):通過 類B: @staticmethod DEF C():A()A_M()'' – Developer 2013-04-25 10:22:12

2

您需要使用完全限定的名稱。此外,在Python 2.7版,則需要使用(object),否則super(A.B)會給TypeError: must be type, not classobj

class A(object): 
    def A_M(self): 
     pass 

    class B(object): 
     @staticmethod 
     def C(): 
      super(A.B).A_M() 

最後,super(A.B)基本上是object這裏。 B是否意味着從A繼承?或者你只是在尋找A.A_M()

+0

不起作用:...錯誤:'def C():super(AB).A_M() TypeError:必須是type,而不是classobj' – Developer 2013-04-25 08:44:36

+0

@Developer:好的,現在再次閱讀我的文章:_「另外,在python 2.7中,你需要使用目的)」_。 'super'只適用於新款式 – Eric 2013-04-25 08:45:59

+0

仍然不起作用:... err:'super(AB).A_M() AttributeError:'super'對象沒有屬性'A_M'' – Developer 2013-04-25 08:50:52

2

一個latecommer,只是封裝在A B簡單的方法是這樣的:

class A: 
    def A_M(self): 
     return "hi" 

    class B: 
     @staticmethod 
     def C(): 
      return A().A_M() 

a = A() 
print a.B().C() 

不知道這是你需要什麼,但問題仍未解決,所以我猜到了。

+0

AB()C()'是不正確。 'a.B.C()'是正確的(因爲C在B中是靜態的)。順便說一句,我投了你的答案。 'gatto'的答案說同樣的事情,但有點冗長。 – Developer 2013-04-25 10:27:40