2016-04-03 22 views
2
class Parent(object): 
    def __init__(self): 
     self.text = "abc" 
     self.child = self.Child() 

    def run(self): 
     self.child.task() 

    def output(self, param1): 
     print(param1) 

    class Child(object): 
     def __init__(self): 
      self.text = "cde" 

     def task(self): 
      Parent.output(Parent, self.text) # I get the warning for this line 


parent = Parent() 
parent.run() 

代碼工作的預期,但IntelliJ IDEA的警告我這個消息 「預計nested_classes.Parent的實例,而不是類本身」 有什麼問題用我的代碼? 謝謝!呼籲父母與嵌套類參數法在python上述

+1

我會推薦在[Code Review](http://codereview.stackexchange.com/)上發佈你的代碼。這裏有很多可以解決的問題。 –

+1

如果您關注ZachGates的評論,請確保在發佈代碼之前不要發佈它。 – zondo

回答

3

您正試圖訪問您的output方法(這是一種實例方法)作爲類方法。由於第一個參數self是實例對象,因此消息即將出現,因此您傳遞class作爲第一個參數實際上會更改self應該具有的實例對象的內容。這就是信息試圖告訴你的。所以,你居然應該做的是調用該方法作爲實例方法:

Parent().output(self.text) 

基於你在做什麼,如果你檢查output方法中的self對象的repr和內容,你得到這樣的:

def output(self, param1): 
    print(repr(self)) 
    print(dir(self)) 
    print(param1) 

使用調用這個方法:Parent.output(Parent, self.text)

<class '__main__.Parent'> 
[ 
    'Child', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', 
    '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', 
    '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
    '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
    '__subclasshook__', '__weakref__', 'output', 'run' 
] 

正如您所見,您的self中沒有instanceParent。現在

,如果你把它作爲一個實例方法:Parent().output(self.text)

<__main__.Parent object at 0x1021c6320> 
[ 
    'Child', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', 
    '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', 
    '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
    '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
    '__weakref__', 'child', 'output', 'run', 'text' 
] 

正如你所看到的,你現在有一個Parent對象,如果你看一下對象的內容,你將有你將期望從您的實例屬性。

+0

感謝您的真棒解釋! –

1

您沒有將輸出聲明爲類方法,所以它期望由父實例調用。