python 类中的方法

python定义一个类

类中可以有 对象方法、类方法、静态方法

对象方法:

我们可以通过类创建实例,这个过程叫做实例化,创建出的对象叫做类的实例,对象的属性叫做实例属性,对象的方法叫做对象方法或实例方法

对象方法:默认有个self参数,可以操作实例属性和类属性 ,只能被实例对象调用。

class Tool(object):

    # 使用赋值语句,定义类属性,记录创建工具对象的总数
    count = 0
    def __init__(self, name):
        self.name = name
        # 针对实例属性做一个计数+1
        self.count += 1


# 创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("榔头")
tool3 = Tool("铁锹")

# 知道使用 tool1实例对象 到底创建了多少个工具?
print("现在创建了 %d 个工具" % tool1.count)
>>>现在创建了 1 个工具

# 知道使用 Tool 类到底创建了多少个对象?
print("现在创建了 %d 个工具" % Tool.count)
>>>现在创建了 0 个工具

在类中再定义一个实例方法,fun()

    def fun(self):             #只能被实例对象调用
        print("实例方法")    

tool1.fun()
>>>实例方法

Tool.fun()
>>>fun() missing 1 required positional argument: 'self'

类方法:

直接访问类属性(用于记录与这个类直接相关的特征)和其他类方法

类方法: 默认有个 cls 参数,可以被类和对象调用,需要加上 @classmethod 装饰器。

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


# 创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("榔头")
tool3 = Tool("铁锹")

# 知道使用 Tool 类到底创建了多少个对象?
print("现在创建了 %d 个工具" % Tool.count)  #类对象直接访问类属性
>>>现在创建了 3 个工具

Tool.show_tool_count()    # 类对象访问类方法
>>>工具对象的总数 3 

 

静态方法: 用 @staticmethod 装饰的不带 self 参数的方法叫做静态方法,类的静态方法可以没有参数,可以直接使用类名调用。

class Tool(object):

    # 使用赋值语句,定义类属性,记录创建工具对象的总数
    count = 0
    @classmethod
    def show_tool_count(cls):
        """显示工具对象的总数"""
        print("工具对象的总数 %d" % cls.count)
        
    @staticmethod
    def staticMethod():
        print("这是一个静态方法")

    def __init__(self, name):
        self.name = name

        # 针对类属性做一个计数+1
        Tool.count += 1


# 创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("榔头")
tool3 = Tool("铁锹")


Tool.staticMethod()
>>>这是一个静态方法

tool1.staticMethod()
>>>这是一个静态方法

 

综合实例:设计一个 Game 类

class Game(object):

    # 游戏最高分,类属性
    top_score = 0

    @staticmethod
    #静态方法,无输入参数,不需要访问类属性和实例属性   
    def show_help(): 
        print("帮助信息:让僵尸走进房间")
        
    @classmethod
    # 类方法,反应Game类的属性 
    def show_top_score(cls):
        print("游戏最高分是 %d" % cls.top_score)
    
    # 实例方法,可以根据此类创建多个实例
    def __init__(self, player_name):
        self.player_name = player_name

    # 实例方法
    def start_game(self):
        print("[%s] 开始游戏..." % self.player_name)
        print("请输入游戏得分:")
        a = int(input())
        if a > Game.top_score:
        # 使用类名.修改历史最高分
            Game.top_score = a

 

# 1. 查看游戏帮助
Game.show_help()
>>>帮助信息:让僵尸走进房间

# 2. 查看游戏最高分
Game.show_top_score()
>>>游戏最高分是 0

# 3. 创建游戏对象,开始游戏
game = Game("小明")
game.start_game()
>>>[小明] 开始游戏...
>>>请输入游戏得分:
45

# 4. 游戏结束,查看游戏最高分
Game.show_top_score()
>>>游戏最高分是 45

#5创建新实例,开始游戏
game = Game("小白")
game.start_game()
>>>[小白] 开始游戏...
>>>请输入游戏得分:
5

#查看此时最高得分
Game.show_top_score()
>>>游戏最高分是 45

 

总结:

  在类中定义 时:

   实例方法可以访问类属性(self.类属性),最好不要这样用,实例方法用于访问类属性,并进行相应操作

  类方法访问类属性(类名或者cls.)

  静态方法无需访问类属性和实例属性

 

  类外使用时:

  实例属性和实例方法只能被实例访问

  

参考博客:https://www.jianshu.com/p/202a289fb2d9

 

posted @ 2020-10-11 14:13  learningcaiji  阅读(359)  评论(0编辑  收藏  举报