Python 3.x 使用类变量和类方法创建实例计数时出现不支持的操作数类型错误
我定义了我的类变量“count\u instance”,以便计算用我的类“Person”创建的实例数。初始化之后,我编写了命令“Person.count_instance+=1”。这样,每次创建新实例时,我的count_实例将增加1 但是,当我创建类的实例(对象)时,它会导致一个错误:“不支持+=:“method”和“int”的操作数类型” 谁能帮帮我为什么会这样?以及如何解决这个问题。我正在使用python 3.6 我试着检查语义和句法错误。但我无法解决这个问题Python 3.x 使用类变量和类方法创建实例计数时出现不支持的操作数类型错误,python-3.x,Python 3.x,我定义了我的类变量“count\u instance”,以便计算用我的类“Person”创建的实例数。初始化之后,我编写了命令“Person.count_instance+=1”。这样,每次创建新实例时,我的count_实例将增加1 但是,当我创建类的实例(对象)时,它会导致一个错误:“不支持+=:“method”和“int”的操作数类型” 谁能帮帮我为什么会这样?以及如何解决这个问题。我正在使用python 3.6 我试着检查语义和句法错误。但我无法解决这个问题 班级人员: count\u实例
班级人员:
count\u实例=0
def uu init uu(self、first_name、last_name、age):#这些是括号中的属性,init是初始化方法。
#实例变量声明
Person.count_实例+=1
self.first\u name=first\u name
self.Last\u name=Last\u name
self.age=年龄
@类方法
def计数_实例(cls):
返回f“您已创建Person类的{cls.count_instance}”
def全名(自我):
返回(f“{self.first\u name}{self.last\u name}”)
def高于18(自身):
返回自我。年龄>18岁
#创建实例
p1=人(“莎拉”、“凯特”,18)
p2=人(“潘卡吉”,“米什拉”,26)
类型错误:+=:'method'和'int'不支持的操作数类型
count\u实例
既是代码中的变量又是方法。对这两者使用唯一的名称。例如,通过将方法更改为打印\u计数\u实例
:
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()
count\u instance
是代码中的变量和方法。对这两者使用唯一的名称。例如,通过将方法更改为打印\u计数\u实例
:
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()
将变量命名为与方法不同的名称。将变量命名为与方法不同的名称。