首先回顾一下Python OOP常见的三种方法:python
标准书写方式以下:git
class MyClass: def method(self): return 'instance method called', self @classmethod def classmethod(cls): return 'class method called', cls @staticmethod def staticmethod(): return 'static method called'
咱们最经常使用的其实就是普通的接口方法,其余两个须要用相似装饰器的写法来标注。github
类方法接受一个cls做为参数,它是指向MyClass自己的,并非MyClass所建立的实例。测试
静态方法不接受self或者cls做为参数,因此不会修改类自己或者实例网站
看一下如何使用类方法,新建一个Pizza类,主要参数为原料ingredientscode
class Pizza: def __init__(self, ingredients): self.ingredients = ingredients def __repr__(self): return f'Pizza({self.ingredients !r})'
新建一个实例测试一下:接口
Pizza(['cheese', 'tomatoes']) Out: Pizza(['cheese', 'tomatoes'])
测试成功。
如今问题来了,既然是Pizza类,会有不一样口味的Pizza,他们的配方都是固定的,那么如何便捷的生成不一样口味的Pizza呢,答案就是classmethodci
class Pizza: def __init__(self, ingredients): self.ingredients = ingredients def __repr__(self): return f'Pizza({self.ingredients!r})' @classmethod def margherita(cls): return cls(['mozzarella', 'tomatoes']) @classmethod def prosciutto(cls): return cls(['mozzarella', 'tomatoes', 'ham'])
类方法能够根据需求事先预约义生成的实例,减小了代码量,这里咱们根据margherita和prosciutto两种口味pizza的原料提早准备好了,cls就是表明类自己,这样若是咱们再生成一些实例时,会方便不少:get
#生成一个margherita口味的pizza m = Pizza.margherita() m Out:Pizza(['mozzarella', 'tomatoes'])
#生成一个prosciutto口味的pizza p = Pizza.prosciutto() p Out:Pizza(['mozzarella', 'tomatoes', 'ham'])
那么何时用静态方法呢? 好比还用这个例子,我想计算pizza的面积:博客
import math class Pizza: def __init__(self, radius, ingredients): self.radius = radius self.ingredients = ingredients def __repr__(self): return (f'Pizza({self.radius!r}, ' f'{self.ingredients!r})') def area(self): return self.circle_area(self.radius) @staticmethod def circle_area(r): return r ** 2 * math.pi
这种状况下使用一个静态方法是一个好的选择,经过area这个普通的接口方法,能够调用circle_area来计算面积,封装性更好:
p = Pizza(4, ['mozzarella', 'tomatoes']) p.area() Out: 50.26548245743669
此次简单总结了类中的三种方法,经过Pizza类的实例方便理解,若是你们有想和我沟通交流的,欢迎留言,或者点击如下连接访问个人网站:
谢谢阅读