python3 多态,绑定方法与非绑定方法

多态:同一种事物的不同形态(一个抽象类有多个子类,因而多态的概念依赖于继承)

1. 序列类型有多种形态:字符串,列表,元组。

2. 动物有多种形态:人,狗,猪

多态性:多态性是指具有不同功能的函数可以使用相同的函数名,这样就可以用一个函数名调用不同功能的函数。

多态性的例子:obj具有多态性

# 以下例子可以概括:多态性就是一个接口(函数func()),多种实现(f.func())
import
abc class Animal(metaclass=abc.ABCMeta): @abc.abstractmethod def talk(self): pass class People(Animal): def talk(self): print('say hello') class Pig(Animal): def talk(self): print('哼哼哼') class Dog(Animal): def talk(self): print('汪汪汪') p1=People() p2=Pig() p3=Dog() def talk(obj):  # 不同的实例化对象obj调用talk()函数,结果不同 obj.talk() talk(p1) talk(p2) talk(p2)
绑定方法:绑定给谁就是给谁用的

绑定到对象的方法:
定义:凡是在类中定义的函数(没有被任何装饰器修饰),都是绑定给对象的,
给谁用:给对象用
特点:obj.bar() 自动把obj当做第一个参数传入,因为bar中的逻辑就是要处理obj


绑定到的方法:
定义:在类中定义的,被classmethod装饰的函数就是绑定到类的方法
给谁用:给类用
特点:类.class_method() 自动把类当做第一个参数传入,因为class_method中的逻辑就是要处理类
class People:
    def __init__(self,name):
        self.name = name
    def bar(self):
        print('---',self.name)

    @classmethod
    def func(cls):
        print(cls)

f = People('egon')
print(People.func)  # 绑定给类
print(f.bar)    #绑定给对象的

People.func()

非绑定方法:用staticmethod装饰器装饰的方法

非绑定方法,就是一个函数,就是一个工具而已,不需要类,也不需对象

import hashlib
import time
class MySQL:
    def __init__(self,host,port):
        self.id=self.create_id()
        self.host=host
        self.port=port
    @staticmethod
    def create_id(): #就是一个普通工具
        m=hashlib.md5(str(time.clock()).encode('utf-8'))
        return m.hexdigest()


print(MySQL.create_id) #<function MySQL.create_id at 0x0000000001E6B9D8> #查看结果为普通函数
conn=MySQL('127.0.0.1',3306)
print(conn.create_id) #<function MySQL.create_id at 0x00000000026FB9D8> #查看结果为普通函数
原文地址:https://www.cnblogs.com/lucaq/p/7127412.html