我刚刚开始学习python中的OOP,并遇到了类方法。我写了一小段代码来确保我能正确理解它。
class Person:
no_of_people = 0
def __init__(self, name):
self.name = name
Person.add_person()
@classmethod
def add_person():
no_of_people += 1
@classmethod
def show_number():
return no_of_people
当我尝试运行代码时,它显示错误消息:
TypeError: add_person() takes 0 positional arguments but 1 was given
但是,当我只是在类方法中插入一个参数时,错误就会消失,并按我的意图运行。
class Person:
no_of_people = 0
def __init__(self, name):
self.name = name
Person.add_person()
@classmethod
def add_person(h):
h.no_of_people += 1
@classmethod
def show_number(h):
return h.no_of_people
有人能向我解释一下为什么吗?
对于类方法,您必须将self作为参数。所以
def add_person(h):
应该是
def add_person(self , h):