0
点赞
收藏
分享

微信扫一扫

python计数属性类

善解人意的娇娇 2023-01-13 阅读 74


class Student:
count=0

def __init__(self,name,age):
self.name=name
self.age=age
Student.count+=1 # 要使得变量全局有效,就定义为类的属性
def learn(self):

print(self.name+'is learning')

stu1 = Student("jack", 33)

stu1.learn()
stu2 = Student("amy", 24)
stu2.learn()

stu3 = Student("lucy", 22)
stu3.learn()

stu4 = Student("lulu", 45)
stu4.learn()


print("实例化了%s个学生" % Student.count)


举报

相关推荐

0 条评论