首页 > 解决方案 > 使用类名和点运算符调用方法

问题描述

当我们在类中定义一个方法并尝试使用 class_name.method_name 访问该方法时,它会显示一个错误,要求为“self”提供参数。例如 prgm 如下:

class a:
    def b(self):
        print('method b')
    def c(self):
        print('method c')
        a.b() #self.b()
d=a()
d.c()
a.c()  #d.c()

在方法b内部和类外部,如果我使用类名a调用方法b,即ac(),它会显示错误如下:

TypeError : b() missing 1 required positional argument: 'self' 

你能解释一下为什么它需要一个“self”的参数,尽管当我们使用对象调用它时我们不需要指定?

标签: pythonmethods

解决方案


当使用对象调用方法时,self参数会自动作为调用对象传递。

当您使用 调用它时class,python 无法了解调用对象是谁,因此,self参数保持为空。

class Foo:
    def bar(self):
        pass

f = Foo()
f.bar()
# or
Foo.bar(f)  # explicitly pass f to the self parameter for it to work

推荐阅读