静态方法
通过 @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 = Person('John')
p.eat()
如果要给 eat() 传参数的话,可以把实例化的 Person 传入
运行结果
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"
class Person(object):
def __init__(self,name):
self.name = name
@staticmethod
def eat(self):
print("%s is eating"%self.name)
if __name__ == '__main__':
p = Person('John')
p.eat(p)
类方法
类方法通过 @classmethod 来定义
类方法只能访问类变量,不能访问实例变量
运行结果
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"
class Person(object):
name = 'Jack'
def __init__(self,name):
self.name = name
@classmethod
def eat(self):
print("%s is eating"%self.name)
if __name__ == '__main__':
p = Person('John')
p.eat()
传入了实例变量 John,但打印的却是 Jack
因为类方法不能访问实例变量,所以类方法访问了类里的类变量
属性方法
通过 @property 来定义属性方法
把类中的方法变为静态属性
按照调用属性的方法来调用属性方法
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"
class Person(object):
def __init__(self,name):
self.name = name
@property
def eat(self):
print("%s is eating"%self.name)
if __name__ == '__main__':
p = Person('John')
p.eat
如果想给属性方法传参数的话,要使用 setter
来源: http://www.bubuko.com/infodetail-2477908.html