4.3 类方法与静态方法,私有属性与私有方法(草稿)
4.3.1 类方法与静态方法
1)类方法和静态方法
一个装饰器只管一个方法
类方法 | 静态方法 | 实例方法 | |
---|---|---|---|
定义 | 类具有的方法,大家都有的特征 | 本质上是函数 与类没有太多联系,与每个具体实例无关 | 不是装饰器修饰的,类里本身的方法 |
装饰器(声明下面的方法是什么方法) | @classmethod | @staticmethod | |
调用 | 类调用 & 实例调用 | 类调用 & 实例调用 | 实例调用(只能) |
类型 | method | function | method |
2)方法,函数,静态方法的区别
方法 | 写在类里面的 |
函数 | 写在类外面的 |
静态方法 | 可以写在外面为了好看写在里面的,本质就是函数 |
3)举例
class Rectangle:def __init__(self, length, width): self.length = length self.width = width def perimeter(self): # 实例方法return (self.length + self.width) * 2def area(self):return self.length * self.width @classmethod # 修饰类方法def features(cls):print('两边的长相等,两边的宽也相等,长和宽的角度是90°')@staticmethod # 修饰静态方法 def fun1(a,b):return a+b # 调用类方法,到时候注释掉 rec = Rectangle(5,4) # 类的实例化 print(rec.perimeter()) # 实例调用实例方法 rec.features() # 实例调用类方法 Rectangle.features() # 类 调用类方法 # 调用静态方法 print(Rectangle.fun1(1,2)) # 类调用静态方法
4)判断对象是方法还是函数(type()和inspect模块)
type() :查看对象是方法还是函数
print(type(rec.perimeter())) # 返回值的类型,是int print(type(rec.perimeter)) # 实例方法是method print(type(rec.features)) # 类方法是method print(type(rec.fun1)) # 静态方法是function
inspect模块,判断对象是否是某个类型,返回值是布尔型
import inspect print(inspect.ismethod(rec.perimeter)) # 返回值不是method? print(inspect.ismethod(rec.features)) # 类方法是method print(inspect.ismethod(rec.fun1)) # 静态方法不是method print(inspect.isfunction(rec.perimeter)) print(inspect.isfunction(rec.features)) print(inspect.isfunction(rec.fun1))