我定义了我的类变量“ count_instance”,以便计算用我的类“ Person”创建的实例数。初始化之后,我编写了命令“ Person.count_instance + = 1”。这样一来,每创建一个新实例,我的count_instance就会增加1。
但是,当我创建类的实例(对象)时,会导致错误提示:“ + =:'method'和'int'的操作数类型不受支持”。
有人可以帮助我为什么会这样吗?以及如何解决此问题。我正在使用python 3.6
我试图检查语义和句法错误。但是我无法解决这个问题。
class Person:
count_instance = 0
def __init__(self, first_name, last_name, age): # These are attributes in the bracket and init is the initialization method.
#Instance Variable declaration
Person.count_instance +=1
self.first_name = first_name
self.Last_name = last_name
self.age = age
@classmethod
def count_instance(cls):
return f"You have created {cls.count_instance} of Person Class"
def full_name(self):
return(f"{self.first_name} {self.last_name}")
def is_above_18(self):
return self.age>18
#Creating the instances
p1 = Person("Sara", "Kat", 18)
p2 = Person("Pankaj", "Mishra", 26)
enter image description here TypeError:+ =:“方法”和“ int”的不受支持的操作数类型
答案 0 :(得分:0)
count_instance
在代码中既是变量又是方法。两者都使用唯一的名称。例如,将方法更改为print_count_instance
:
class Person:
count_instance = 0
def __init__(self, first_name, last_name, age): # These are attributes in the bracket and init is the initialization method.
#Instance Variable declaration
Person.count_instance +=1
self.first_name = first_name
self.Last_name = last_name
self.age = age
@classmethod
def print_count_instance(cls):
return f"You have created {cls.count_instance} of Person Class"
def full_name(self):
return(f"{self.first_name} {self.last_name}")
def is_above_18(self):
return self.age>18
#Creating the instances
p1 = Person("Sara", "Kat", 18)
p2 = Person("Pankaj", "Mishra", 26)
p1.print_count_instance()