静态方法
通过@staticmethod来定义,静态方法在类中,但在静态方法里访问不了类和实例中的属性,但静态方法需要类来调用
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"
class Person(object):
def __init__(self,name):
self.name = name
@staticmethod
def eat(self,food):
print("%s is eating %s"%(self.name,food))
if __name__ == '__main__':
p = Person('John')
p.eat('meat')
运行,报错
把eat方法的参数去掉,直接打印,可以直接调用
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"
class Person(object):
def __init__(self,name):
self.name = name
@staticmethod
def eat():
print("John is eating")
if __name__ == '__main__':
p = Perso