python中的静态方法

问题:pycharm中建立新的方法,出现如下的警告:
在这里插入图片描述
在python中建立类一般使用如下的方法:

class Dog(object):
    def run(self):
        print("running")

run方法是类中的普通方法

声明和创建静态方法,在方法上加上staticmethod注明一下

class Dog(object):
    @staticmethod
    def run(self):
        print("running")

如下的声明方式是错误的:

class Dog(object):
    @staticmethod
    def run(self):
        print("running")
Dog.run()

修改方式为:

class Dog(object):
    @staticmethod
    def run():
        print("running")
Dog.run()

其中要必须把self去掉,除此之外:
class Dog(object):

    def swim():
        print("swimming")
Dog.swim()

这样也可以,但是不建议这么做,因为具体不能分清楚是是什么方法。
如下

class Dog(object):
    @staticmethod
    def run():
        print("running")
    def swim(self):
        print("swimming")
        
Dog.run()
dog = Dog()
dog.swim()

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

发布了84 篇原创文章 · 获赞 29 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_39852676/article/details/103905297