# ===================== 类:正确使用方式1 ========================
class Student1():
# 功能:有默认参数,实例化时,也可传入参数
def __init__(self,name = "张三",score=99):
self.name = name
self.score = score
def add(self):
return self.score * 2
# ===================== 类:正确使用方式2 ========================
class Student2():
# 功能:实例化时,需要传入参数
def __init__(self,name,score):
self.name = name
self.score = score
def add(self):
return self.score * 2
# ===================== 类:正确使用方式3 ========================
class Student3():
# 功能:实例化时不能传入参数
def __init__(self):
self.name = "高启强"
self.score = 2000
def add(self):
return self.score * 2
# ===================== 类:正确使用方式4 ========================
if __name__ == '__main__':
Student = Student1("李四",10)
print("Student1:",Student.add())
Student = Student2("李四",10)
print("Student2:",Student.add())
Student = Student3()
print("Student3:",Student.add())
类的简单使用
最新推荐文章于 2023-09-03 10:00:00 发布
文章展示了Python中类的四种不同使用方式,包括带有默认参数的初始化,必须传入参数的初始化,无参数的初始化以及如何定义和调用对象的方法。通过创建Student类并实例化,演示了如何通过这些方法操作对象属性。
摘要由CSDN通过智能技术生成