面向对象
类,属性,方法,对象体验
# 类,属性,方法,对象体验
class Student:
no = 0
name = ""
age = 0
def print(self, no, name, age):
self.no = no
self.name = name
self.age = age
print(f"学号:{self.no},姓名:{self.name}年龄:{self.age}")
# 创建对象
student = Student()
# 调用方法
student.print(1, "张三", 20)
构造方法是自动调用的
class Student:
no = 0
name = ""
age = 0
# 构造方法
def __init__(self, no, name, age):
self.no = no
self.name = name
self.age = age
# 打印方法
def print_info(self):
print(f"学号:{self.no},姓名:{self.name}年龄:{self.age}")
# 创建对象
student = Student(1, "张三", 20)
# 调用方法
student.print_info()
这个方法类似java中的重写tostring方法
class Student:
def __str__(self):
return "类似重写java中的tostring方法"
# 创建对象
student = Student()
print(student)
__del__方法是被系统自动调用
# 类和对象练习
class SweetPotato:
# 构造方法
def __init__(self):
self.countTime = 0
self.status = "生的"
self.condiments = []
# 业务方法
def cook(self, time):
self.countTime += time
if 0 <= self.countTime < 3:
self.status = "生的"
elif 3 <= self.countTime < 5:
self.status = "半生不熟"
elif 5 <= self.countTime < 8:
self.status = "熟了"
elif self.countTime >= 8:
self.status = "糊了"
# 业务方法
def condiment_info(self, condiment):
self.condiments.append(condiment)
# tostring方法
def __str__(self):
return f"时间为:{self.countTime}分钟,状态为:{self.status},调料为:{self.condiments}"
# 创建对象
sweetPotato = SweetPotato()
sweetPotato.cook(2)
sweetPotato.condiment_info("酱油")
print(sweetPotato)
sweetPotato.cook(2)
sweetPotato.condiment_info("味精")
print(sweetPotato)
sweetPotato.cook(2)
sweetPotato.condiment_info("食盐")
print(sweetPotato)
sweetPotato.cook(2)
print(sweetPotato)
END