python中的静态方法

问题:pycharm中建立新的方法,出现如下的警告:
python中的静态方法_第1张图片
在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()

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

你可能感兴趣的:(python)