如何在PYTHON里定义静态方法

时间:2026-02-17 17:37:07

1、新建一个PY文档。

如何在PYTHON里定义静态方法

2、class Dog(object):

    def run(self):

        print("running")

        

#这是我们一般创建类的写法。

如何在PYTHON里定义静态方法

3、class Dog(object):

    @staticmethod

    def run(self):

        print("running")

        

#如果要创建静态方法,那么要加上staticmethod注明一下。

如何在PYTHON里定义静态方法

4、class Dog(object):

    @staticmethod

    def run(self):

        print("running")

        

Dog.run()

#但是现在还不能进行调用。这样写是错误的。

如何在PYTHON里定义静态方法

5、class Dog(object):

    @staticmethod

    def run():

        print("running")

        

Dog.run()

#我们必须要把self去掉。

如何在PYTHON里定义静态方法

6、class Dog(object):

    def swim():

        print("swimming")

        

Dog.swim()

#如果这样写也是能运行,但是不建议这样,因为分不清楚具体是什么方法。

如何在PYTHON里定义静态方法

7、class Dog(object):

    @staticmethod

    def run():

        print("running")

    def swim(self):

        print("swimming")

        

Dog.run()

dog = Dog()

dog.swim()

#静态方法是可以和对象方法并存的。

如何在PYTHON里定义静态方法

© 2026 一点资料
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com