• day30---绑定方法与非绑定方法


    1、绑定方法


    (1)对象的绑定方法

    在类中正常定义的函数是绑定给对象的

       def save_info(self):
            stu_data_dir = common.student_data_dir
            stu_data_path = os.path.join(stu_data_dir, f'{self.name}.pkl')
            if not os.path.exists(stu_data_dir):
                os.makedirs(stu_data_dir)
            else:
                if os.path.exists(stu_data_path):
                    raise Exception(f'{self.name}.pkl已存在,保存失败!')
            with open(stu_data_path, mode='wb') as stu_file:
                pickle.dump(self, stu_file)

    对象在调用该方法时,会自动将对象作为第一个参数传入

    (2)类的绑定方法

    为类中的某个函数加上装饰器@classmethod后,该函数就绑定到了类。

    # 配置文件settings.py的内容
    HOST='127.0.0.1'
    PORT=3306
    
    # 类方法的应用
    import settings
    class MySQL:
        def __init__(self,host,port):
            self.host=host
            self.port=port
        @classmethod
        def from_conf(cls): # 从配置文件中读取配置进行初始化
            return cls(settings.HOST,settings.PORT)
    
    >>> MySQL.from_conf # 绑定到类的方法
    <bound method MySQL.from_conf of <class__main__.MySQL'>>
    >>> conn=MySQL.from_conf() # 调用类方法,自动将类MySQL当作第一个参数传给cls

    2、非绑定方法


    为类中某个函数加上装饰器@staticmethod后,该函数就变成了非绑定方法,也称为静态方法。该方法不与类或对象绑定,类与对象都可以来调用它,但它就是一个普通函数而已,因而没有自动传值那么一说

    import uuid
    class MySQL:
        def __init__(self,host,port):
            self.id=self.create_id()
            self.host=host
            self.port=port
        @staticmethod
        def create_id():
            return uuid.uuid1()
    
    >>> conn=MySQL(‘127.0.0.1',3306)
    >>> print(conn.id) #100365f6-8ae0-11e7-a51e-0088653ea1ec
    
    # 类或对象来调用create_id发现都是普通函数,而非绑定到谁的方法
    >>> MySQL.create_id
    <function MySQL.create_id at 0x1025c16a8>
    >>> conn.create_id
    <function MySQL.create_id at 0x1025c16a8>
  • 相关阅读:
    计算机组成原理
    数据结构和算法: 字符串匹配(一) BF/RK
    数据结构和算法: 动态规划-台阶问题
    数据结构和算法: 散列表
    数据结构和算法: 归并排序/快速排序
    数据结构与算法: 冒泡/插入/选择排序
    过渡内容
    Redis 和缓存技术
    2019字节跳动面试时手撕代码题
    Mysql锁机制
  • 原文地址:https://www.cnblogs.com/surpass123/p/12678745.html
Copyright © 2020-2023  润新知