Python:由實例對象調用方法:“missing 1 required positional argument:'self'” [英] Python: Call method by instance object: "missing 1 required positional argument: 'self'"

查看:16666
本文介紹了Python:由實例對象調用方法:“missing 1 required positional argument:'self'”的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我是Python的新手。我寫了兩個類,第二個有第一個的一個實例作為成員變量?,F在我想通過它的類的一個實例調用Class2的方法。我找不到答案。類似這樣:

I'm new to Python. I've written two Classes, the second one has an instance of the first one as a member variable. Now I want to call a method of Class2 via the instance of it in class one. I could not find an answer for it. Something like this:

class Class1:
    def uselessmethod(self):
        pass

class Class2:
    def __init__(self):
        self.c = Class1()

    def call_uselessmethod(self):
        self.c.uselessmethod()

k = Class2
k.call_uselessmethod() # Error!

出現以下錯誤:

k.call_uselessmethod() #Error
TypeError: call_uselessmethod() missing 1 required positional argument: 'self'

這里有什么想法?提前感謝。

Any idea of what is going on here? Thanks in advance.

推薦答案

call_uselessmethod 要求首先有一個實例 Class2 。但是,這樣做:

call_uselessmethod requires that there first be an instance of Class2 before you use it. However, by doing this:

k = Class2

您不會將 k 分配給 Class2 的實例, Class2 本身。

you are not assigning k to an instance of Class2 but rather Class2 itself.

創建 Class2 ,在類名后添加()

To create an instance of Class2, add () after the class name:

k = Class2()
k.call_uselessmethod()

現在,您的代碼將工作,因為 k 指向 Class2 的實例。

Now, your code will work because k points to an instance of Class2 like it should.

這篇關于Python:由實例對象調用方法:“missing 1 required positional argument:'self'”的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!

查看全文
相關文章
登錄 關閉
掃碼關注1秒登錄
發送“驗證碼”獲取 | 15天全站免登陸
全免费A级毛片免费看无码播放