Python的类、方法、函数、多态

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、类方法 静态方法 函数

Python中函数和方法区别

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'>>
  1. 当类直接调用function时
    • 定义在@staticmethod下的函数(func2)和普通函数(func1)属于函数
    • 定义在@classmethod下的函数(func3),属于方法(即称为类方法)。
  2. 当类实例化生成对象后(apple),再调用函数时
    • 普通函数(fun1),就被称为是实例化方法
    • 定义在@staticmethod下的函数(func2),与 class 和实例化对象无关,所以依然属于函数
    • 定义在@classmethod下的函数(func3),与class内部有关,属于类的方法

总结

  1. 定义在类中的静态方法@staticmethod一直是函数。

  2. 定义在类中的类方法@classmethod一直是类方法。

  3. 定义在类中的普通方法,由类来调用时它是函数,通过实例调用时它是方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值