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

查看:16426
本文介绍了Python:由实例对象调用方法:“missing 1 required positional argument:'self'”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手。我写了两个类,第二个有第一个的一个实例作为成员变量。现在我想通过它的类的一个实例调用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天全站免登陆