创建对象的过程
- 每一个对象都有自己独立的空间,保存各自不同的属性。
- 多个对象的方法,在内存中只有一份,在调用对象方法时,需要把对象的引用传递到方法内部。
类是一个特殊的对象
- 在程序运行时,类同样会被加载到内存
- 在python中,类是一个特殊的对象,类对象
- 在程序运行中,类在内存中只有一份,使用一个类可以创建多个实例对象
- 除了封装对象的属性和方法外,类还可以封装自己的类属性和类方法
class Tool(object):
# 使用赋值语句定义类属性,记录所有工具对象的数量
count = 0
def __init__(self, name):
self.name = name
# 让类属性的值+1
Tool.count += 1
# 1. 创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("榔头")
# 2. 输出工具对象的总数
print(Tool.count)
# 属性的向上查找机制,首先在当前实例对象查找,没有往父类找,一直找到类对象为止
#print(tool1.count) # 不推荐使用
在python中,属性的查找存在一个向上查找的机制。
类方法
- 类方法需要使用@classmethod来修饰
- 类方法的第一个参数必须是cls
- 在方法内部,可以使用cls.来调用类的方法和属性
语法
@classmethod
def 类方法名(cls):
pass
class Tool(object):
# 使用赋值语句定义类属性,记录所有工具对象的数量
count = 0
# 类方法定义
@classmethod
def show_tool_count(cls):
print("工具对象的数量 %d" % cls.count)
def __init__(self, name):
self.name = name
# 让类属性的值+1
Tool.count += 1
# 1. 创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("榔头")
Tool.show_tool_count()
静态方法
在开发中,如果需要定义一个方法
- 既不会访问对象属性或者调用对象方法
- 也不会访问类属性或者调用类方法
这个时候可以把这个方法封装成静态方法
特点:
使用@staticmethod修饰,告诉解释器这是一个静态方法
通过类名.调用静态方法
语法
@staticmethod
def 静态方法():
pass
class Dog(object):
@staticmethod
def run():
print("小狗快跑")
# 调用静态方法
Dog.run()
class Game(object):
# 历史最高分
top_score = 0
def __init__(self, player_name):
self.player_name = player_name
@staticmethod
def show_help():
print("帮助信息:让僵尸进入大门")
@classmethod
def show_top_score(cls):
print("历史记录 %d" % cls.top_score)
def start_game(self):
print("%s 开始游戏啦..." % self.player_name)
Game.show_help()
Game.show_top_score()
game = Game("小明")
game.start_game()
- 方法内部需要访问到对象属性,对象方法
- 方法内部只需要访问到类属性,类方法
- 都不访问,静态方法