Python 的类、方法、函数、多态
如何定义类
import time
import random
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
a = AverageMeter() # 类的实例化
for i in range(10):
begin = time.time()
time.sleep(random.randint(1,10))
a.update(time.time() - begin) # 使用类的方法
print('Data {a.val:.3f} ({a.avg:.3f})\t'.format(a=a))
1、类的继承 方法重构 多态
多态:通俗理解,经一个父类构建多个子类,子类在部分特性上有些不同。比如用Animal类构建Cat类和Dog类。
Python入门 class类的继承
关于继承和方法重构
# 父类定义,继承自object
class Animal(object):
def __init__(self,name,age):
self.name = name
self.age = age
def call(self): # 方法的定义
print(self.name,'会叫')
'''类的继承'''
# 子类定义
class Cat(Animal):
def __init__(self,name,age,gender):
# 初始化父类,从父类 Animal的__init__()方法中引入属性
super(Cat,self).__init__(name,age) # 方法一
# Animal.__init__(self,name,age) # 方法二
self.gender = gender
'''子类方法的重构'''
def call(self):
print(self.name,'会喵喵叫')
if __name__ == '__main__':
c = Cat('加菲猫', 2, '男') # 类的实例化
c.call() # 实例的方法
2、类方法 静态方法 函数
2.1 单独定义的func都属于函数
def fun():
print('hi')
print(fun) # <function fun at 0x7f473478bca0>
fun() # hi
print(fun()) # hi None
2.2 在类中定义的函数
class Apple:
def fun1(self): # ⭐
return 'normal'
@staticmethod
def fun2(self):
return 'staticmethod'
@classmethod
def fun3(self):
return 'classmethod'
print(Apple.fun1) # <function Apple.fun1 at 0x7f465fd57820>
print(Apple.fun2) # <function Apple.fun2 at 0x7f465fd57790>
print(Apple.fun3) # <bound method Apple.fun3 of <class '__main__.Apple'>>
print('——————')
apple = Apple()
print(apple.fun1) # <bound method Apple.fun1 of <__main__.Apple object at 0x7f465fd9dbb0>>
print(apple.fun2) # <function Apple.fun2 at 0x7f465fd57790>
print(apple.fun3) # <bound method Apple.fun3 of <class '__main__.Apple'>>
- 当类直接调用function时
- 定义在
@staticmethod
下的函数(func2)和普通函数(func1)属于函数
。- 定义在
@classmethod
下的函数(func3),属于方法
(即称为类方法
)。- 当类实例化生成对象后(apple),再调用函数时
- 普通函数(fun1),就被称为是
实例化方法
。- 定义在
@staticmethod
下的函数(func2),与 class 和实例化对象无关
,所以依然属于函数
。- 定义在
@classmethod
下的函数(func3),与class内部有关
,属于类的方法
。总结
定义在类中的静态方法
@staticmethod
一直是函数。定义在类中的类方法
@classmethod
一直是类方法。定义在类中的普通方法,
由类来调用时它是函数,通过实例调用时它是方法
。