Thomas Bergersen - Heart of Courage(纯音乐版).mp3
01:58
来自极客饕餮
一 类方法
当目前为止,我们所看到的对象的方法被一个类的实例所调用,然后被传递给方法的self参数.
类方法是不同的--它们被一个类所调用,它被传递给方法的"cls"参数.
类方法用classmethod装饰器标记.
例如:
class Rectangle:
def __init__(self,width,height):
self.width=width
self.height=height
def calculate_area(self):
return self.width*self.height
@classmethod
def new_square(cls,side_length):
return cls(side_length,side_length)
square=Rectangle.new_square(5)
print(square.calculate_area())
结果:25
new_square是一个类方法,在类上调用,而不是在类的实例上调用.它返回cls的新对象.
从技术上说,参数self和cls只是惯例;它们可以改变为其他任何东西.然而,它们是普遍被遵循的,所以还是固定是用self和cls当参数.
二 静态方法
静态方法与类方法类似,只是它们没有收到任何额外的参数.
它们用staticmethod装饰器标记.
例如:
class Pizza:
def __init__(self,toppings):
self.toppings=toppings
@staticmethod
def validate_toppings(toppings):
if toppings=="pineapple":
raise ValueError("pineapple")
else:
print ("no pineapple")
ingredients=["cheese","onions","spam",]
if all(Pizza.validate_toppings(i) for i in ingredients):
pizza=Pizza(ingredients)
结果:
no pineapple
静态方法:没有self或cls参数.
三 属性
属性提供了一种自定义实例属性访问的方法.
它们是通过将属性装饰器放在一个方法上面创建的.这意味着当访问与方法同名的实例属性时,方法将被调用.
属性的一种常见用法就是使属性为只读
例如:
class Pizza:
def __init__(self,toppings):
self.toppings=toppings
@property
def pineapple_allowed(self):
return False
pizza=Pizza(["cheese","tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed=True
结果:
这样pineapple_allowed就成了一个只读属性.
★属性也可以通过定义setter/getter函数来设置.
setter函数设置相应的属性值.
getter函数获取相应的属性值.
要定义一个setter,你需要使用一个与属性名相同的装饰器,后面跟着一个点和setter关键字
这同样适用于getter函数
例如:
class Pizza:
def __init__(self,toppings):
self.toppings=toppings
self._pineapple_allowed=False
@property
def pineapple_allowed(self):
return self._pineapple_allowed
@pineapple_allowed.setter
def pineapple_allowed(self,value):
if value:
password=input("请输入密码:")
if password=="极客饕餮":
self._pineapple_allowed=value
print(pizza.pineapple_allowed)
else:
raise ValueError("警报,入侵者!")
pizza=Pizza(["cheese","tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed="任何一个不为假的字符串"
结果: