02-类和对象
类的属性和方法
类的属性:对象的特征描述(实际上为类中定义的变量,该变量为属性)
类的方法:对象具有的行为(本质是函数),类中定义的函数即方法
class Student(object):
name = "lucy" # 属性
def info(self): # 方法
print(f"{self.name} 的信息...")
print(Student.__dict__) # 查看类的属性
print(Student.__dict__['name']) # 查看单个属性name的内容
# 增删改查类中的单个属性
print(Student.name)
Student.name = "Willa" # 修改
print(Student.name)
del Student.name # 删除属性
print(Student.__dict__) # 查看是否还有 name 属性
# 给类添加属性
Student.walk = "走路"
print(Student.walk)
输出:
{'__module__': '__main__', 'name': 'lucy', 'info': <function Student.info at 0x0000019DDC0F8360>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}
lucy
lucy
Willa
{'__module__': '__main__', 'info': <function Student.info at 0x0000019DDC0F8360>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}
走路
小结:属性有则覆盖,无则添加。使用的是类名.属性
对象的属性和方法
# 定义类(创建类)
class Hero(object):
def move(self):
print("正在前往...")
# 创建对象,实例化对象
hero = Hero()
# 给对象添加属性
hero.name = "盖伦" # 添加对象的name属性
hero.hp = 100 # 生命值
print('英雄%s的生命值:%d' % (hero.name, hero.hp))
# 调用实例方法
hero.move()
输出:
英雄盖伦的生命值:100
正在前往...