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类方法、静态方法与实例方法
  • 如何取消Oracle 11g的限制
  • python程序打包成exe
  • 如何使用VirtualBox新建虚拟机?
  • 如何使用maven运行spring boot 项目
  • 如何使用SQLyog从CSV文件导入表数据
  • 热门搜索
    无房产证明怎么开 win7屏幕亮度怎么调 皮肤角质层薄怎么修复 雅芳化妆品怎么样 天猫怎么给差评 辽宁旅游景点大全 怎么共享网络打印机 华为麦芒4怎么样 便秘肚子胀怎么办 五台山旅游图