PYTHON里同时运用实例方法、类方法和静态方法

 时间:2026-04-23 15:58:30

1、class Animal(object):

    result = 1

    

#首先创建一个类,然后我们定义一下类属性。

PYTHON里同时运用实例方法、类方法和静态方法

2、class Animal(object):

    result = 1

    def __init__(self, name):

        self.name = name

        

#然后我们进行初始化,设置实例的属性。

PYTHON里同时运用实例方法、类方法和静态方法

3、class Animal(object):

    result = 1

    def __init__(self, name):

        self.name = name

    @staticmethod

    def welcome():

        print("welcome to the Zoo!")

        

#然后我们就可以设置一下静态方法了,静态方法不调用实例属性和类属性。

PYTHON里同时运用实例方法、类方法和静态方法

4、class Animal(object):

    result = 1

    def __init__(self, name):

        self.name = name

    @staticmethod

    def welcome():

        print("welcome to the Zoo!")

    @classmethod

    def total(cls):

        print("the total animal is %d." % cls.result)

        

#创建类方法就可以调用类属性。

PYTHON里同时运用实例方法、类方法和静态方法

5、class Animal(object):

    result = 1

    def __init__(self, name):

        self.name = name

    @staticmethod

    def welcome():

        print("welcome to the Zoo!")

    @classmethod

    def total(cls):

        print("the total animal is %d." % cls.result)

    def play(self):

        print("playing with %s." % self.name)

        

#最后就是创建实例方法,调用实例的属性。

PYTHON里同时运用实例方法、类方法和静态方法

6、class Animal(object):

    result = 1

    def __init__(self, name):

        self.name = name

    @staticmethod

    def welcome():

        print("welcome to the Zoo!")

    @classmethod

    def total(cls):

        print("the total animal is %d." % cls.result)

    def play(self):

        print("playing with %s." % self.name)

Animal.welcome()

Animal.total()

lion = Animal("Lion")

lion.play()

#这个时候就能同时运用三种方法了。

PYTHON里同时运用实例方法、类方法和静态方法

  • PyCharm中Flake8工具的配置
  • VS Code中怎么添加Emacs的快捷键
  • 线程如何进入运行状态
  • c#如何把excel通过winfrom导入到数据库中
  • SQL Server配置管理器的重新启动
  • 热门搜索
    微波炉怎么蒸鸡蛋 腿短怎么办 妇科炎症怎么治疗 电脑无法关机怎么办 离职原因怎么写最合适 白苹果怎么修复 怎么更改电脑用户名 第三人称转述句怎么改 星座是怎么算的 苹果蓝牙怎么连接