Python类方法、静态方法与实例方法

2024-10-13 15:55:19

1、打开编辑器(sublime text 3),新建一个py文档。

Python类方法、静态方法与实例方法

2、class Game(): def __init__(self, name): self.name = name def greeting(self): print("Hello! Welcome %s." %(self.name))peter = Game("Peter")peter.greeting()首先最基本最常见的是实例方法,重点就是在这个self。

Python类方法、静态方法与实例方法

3、class Game(): @staticmethod def greeting(): print("Hello!")静态方法的时候要加入@staticmethod,并且不用加self。

Python类方法、静态方法与实例方法

4、class Game(): people = 99 @classmethod def greeting(cls): print("Total people is %d." %(cls.people))类方法需要加入@classmethod,并且把self改为cls,调用的时候也要用cls。

Python类方法、静态方法与实例方法

5、class Game(): people = 99 @classmethod def greeting(cls): print("Total people is %d." %(cls.people))Game.greeting()类属性调用的时候要写class的名字来调用。

Python类方法、静态方法与实例方法

6、class Game(): @staticmethod def greeting(): print("Hello!")Game.greeting()同样调用静态方法的时候也是需要写类的名字。

Python类方法、静态方法与实例方法
猜你喜欢