Discuss / Python / 关于static

关于static

Topic source

大冰小松

#1 Created at ... [Delete] [Delete and Lock User]
class Animal(object):
    def run(self):
        print('Animal is running')

各位,我是用的ide写, 编译器提示 Method 'run' may be static。那位大神解释一下,python中static的概念,感激不尽。

葛斯特

#2 Created at ... [Delete] [Delete and Lock User]

static的意思是“静态”的,意思就是说,这个类的方法不需要作为实例就能运行,运行方式看下面代码:(注意run()必须要有一个object参数才能运行)

class Animal(object):
    def run(self):
        print('Animal is running')

Animal.run(Animal)

在java里static是一个关键字,写上了就说明这个方法是“静态的”,只能通过“类名.方法名”的方式调用,实例是调用不了的,而如果不写就说明这个方法是“动态的”,只能通过“实例.方法名”的方式调用,通过“类名.方法名”调用会报错。而在python里没这么严格,上面代码里的run()既可以是动态的也可以是静态的。

小样还逃

#3 Created at ... [Delete] [Delete and Lock User]

Java里静态方法也是可以通过"实例.方法名"的方法调用的,只是一般都用"类名.方法名"来调用。但动态方法就不能用"类名.方法名"来调用了。


  • 1

Reply