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

2025-10-02 02:00:26

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类方法、静态方法与实例方法

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢