7th step for python:class parament && class function && static function

     
class Tool():
     count = 0
    def __init__(self, name):
        self.name = name
         Tool.count += 1

a = Tool("a")
b = Tool("b")
print(Tool.count)
like the globe parament ,but it is for a class ,not for the object
when a function just uses the class parament ,we can made a class function

class function:
this function is for the class to use not for object

class Tools:
    counts = 0

    @classmethod #this one mark this function is class function
    def show_tool_count(cls):
        print("tools object number: %d" % cls.counts)

    def __init__(self, name):
        self.name = name
        Tools.counts += 1
    
        @staticmethod# this mark this function is stantic function
         def use():
                print ( "use" )


t = Tools("t")
Tools.show_tool_count()

static function:
if a function need not the object's parament or class parament ,we can made it static function

here is a simple show:
class Game(object):
top_score = 0
    def __init__(self, player_name):
        self.player_name = player_name
    @staticmethod
    def show_help():
        print("help information: let the zombie enter the door")
    @classmethod
    def show_top_score(cls):
        print("history %d"%cls.top_score)
    def start_game(self):
        print("%s start games..."%self.player_name)
Game.show_help()
Game.show_top_score()
g = Game("xm")
g.start_game()

猜你喜欢

转载自blog.csdn.net/qq_14942375/article/details/80729134