静态方法
通过@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
格式:@属性方法名.setter
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"
class Person(object):
def __init__(self,name):
self.name = name
self.__food = None #设置一个私有属性
@property
def eat(self):
print("%s is eating %s"%(self.name,self.__food))
#名称要与属性方法的一样
@eat.setter
def eat(self,food):
print("Set the food:%s"%food)
self.__food = food
if __name__ == '__main__':
p = Person('John')
p.eat
p.eat = 'meat' #通过赋值的方法来传参数,并调用用来传参数的eat方法
p.eat
运行结果
![]()
最先是None,经过赋值传参数后为meat
要删除属性方法的属性,可以使用deleter
格式:@属性方法名.deleter
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"
class Person(object):
def __init__(self,name):
self.name = name
self.__food = None #设置一个私有属性
@property
def eat(self):
print("%s is eating %s"%(self.name,self.__food))
#名称要与属性方法的一样
@eat.setter
def eat(self,food):
print("Set the food:%s"%food)
self.__food = food
@eat.deleter
def eat(self):
del self.__food
print('Del the food ok!')
if __name__ == '__main__':
p = Person('John')
p.eat
p.eat = 'meat' #通过赋值的方法来传参数,并调用用来传参数的eat方法
p.eat
del p.eat #调用@eat.deleter来删除属性方法eat的food属性
p.eat
运行结果
![]()
前四条语句成功执行,删除food属性后,第五条语句没有food属性,报错