1、静态方法
- 通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法;
- 实际上和类没什么关系,唯一的关联就是需要通过类来调用;
- 在名义上面归类管理,实际上在静态方法里面访问不了类或实例中的任何属性
# Author: Mr.Xue
# 2019.10.29
class Dog(object):
"""this is a class: Dog"""
def __init__(self, name):
self.name = name
@staticmethod # 静态方法
def eat(self, food):
#2. 在eat方法中去掉self参数,但这也意味着,在eat中不能通过self.调用实例中的其它变量了
print("%s is eating %s" % (self.name, food))
#1. 调用时主动传递实例本身给eat方法
d.eat(d, 'baozi') #与类无关,所以调用时传入对象本身
2、类方法
类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量
# Author: Mr.Xue
# 2019.10.29
class Dog(object):
name = 'huazai' # 类变量
def __init__(self, name):
self.name = name # self.name: 实例变量
@classmethod
def eat(self):
print("%s is eating" % self.name)
d = Dog("Bob")
d.eat()
程序结果输出"huazai is eating",而非"Bob is eating"
场景:国籍,不允许改国籍之类的
3、属性方法
属性方法通过@property装饰器实现,把一个方法变成一个静态属性
# Author: Mr.Xue
# 2019.10.29
class Dog(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 # 属性方法中的set
def eat(self, food):
print("set to food: ", food)
self.__food = food
@eat.deleter # 属性方法中的delete
def eat(self):
del self.__food
print('delete ok')
d = Dog("Bob")
d.eat # 调用属性方法,给用户呈现的效果就像调用变量一样
d.eat = 'baozi' # 调用属性方法中的set
d.eat
del d.eat # 调用属性方法中的delete
d.eat
输出结果为:
Bob is eating None
set to food: baozi
Bob is eating baozi
delete ok
Traceback (most recent call last):
File "property_method.py", line 29, in <module>
d.eat
File "property_method.py", line 12, in eat
print("%s is eating %s" % (self.name, self.__food))
AttributeError: 'Dog' object has no attribute '_Dog__food'
示例:航空公司航班信息查询
# Author: Mr.Xue
# 2019.10.29
class Flight(object):
def __init__(self, flight_name):
self.flight_name = flight_name
def check_status(self):
print("checking flight %s status" % self.flight_name)
return 1
@property
def flight_status(self):
status = self.check_status()
if status == 0:
print('0')
elif status == 1:
print('1')
else:
print('error')
f = Flight('A847')
f.flight_status