一个 Student 类可以创建 N 个Student类的实例对象,每个实例对象的属性值不同。
# 作 者:要努力,努力,再努力
# 开发日期:2022/4/23 14:32
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(self.name + '在吃饭')
stu1 = Student('张珊', 20)
stu2 = Student('李四', 30)
print(id(stu1), id(stu2))
print('-------------------动态绑定属性----------------------')
stu2.gender = '女'
print(stu1.name, stu1.age)
# print(stu1.name, stu1.age, stu1.gender) # AttributeError: 'Student' object has no attribute 'gender'
print(stu2.name, stu2.age, stu2.gender)
print('--------------------------------------')
stu1.eat()
stu2.eat()
def show():
print('定义在类之外,是函数')
print('-------------------动态绑定方法----------------------')
stu1.show = show
stu1.show()
# stu2.show() # AttributeError: 'Student' object has no attribute 'show'