zoukankan      html  css  js  c++  java
  • python学习-----8.22--classmethod和staticmethod

    一、绑定方法

      1.绑定到类的方法:用classmethod装饰器装饰的方法。为类量身定制

        类.boud_method(),自动将类当作第一个参数传入

        (其实对象也可调用,但仍将类当做第一个参数传入)

        2.绑定到对象的方法:没有任何装饰器装饰的方法。为对象量身定制

        对象.boud_method(),自动将对象当做第一个参数传入

        (属于类的函数。类可以调用,但必须按照函数的规则来,没有自动传值那么一说)

    HOST='127.0.0.1'
    PORT=3306
    DB_PATH=r'C:UsersAdministratorPycharmProjects	est面向对象编程	est1db'
    View Code
    import settings
    class MySQL:
        def __init__(self,host,port):
            self.host=host
            self.port=port
    
        @classmethod
        def from_conf(cls):
            print(cls)
            return cls(settings.HOST,settings.PORT)
    
    print(MySQL.from_conf) #<bound method MySQL.from_conf of <class '__main__.MySQL'>>
    conn=MySQL.from_conf()
    
    conn.from_conf() #对象也可以调用,但是默认传的第一个参数仍然是类
    View Code

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

      1.不与类或对象绑定,类和对象都可以调用,但是没有自动传值那么一说,就是一个普通工具而已

        注意:与绑定到对象方法区分开,在类中直接定义的函数,没有被任何装饰器装饰的,都是绑定到对象的方法,可不是普通函数,对象调用该方法会自动传值,,而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.time()).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> #查看结果为普通函数
    复制代码
    View Code

    classmethod与staticmethod的区别

    import settings
    class MySQL:
        def __init__(self,host,port):
            self.host=host
            self.port=port
    
        @staticmethod
        def from_conf():
            return MySQL(settings.HOST,settings.PORT)
    
        # @classmethod #哪个类来调用,就将哪个类当做第一个参数传入
        # def from_conf(cls):
        #     return cls(settings.HOST,settings.PORT)
    
        def __str__(self):
            return '就不告诉你'
    
    class Mariadb(MySQL):
        def __str__(self):
            return '<%s:%s>' %(self.host,self.port)
    
    
    m=Mariadb.from_conf()
    print(m) #我们的意图是想触发Mariadb.__str__,但是结果触发了MySQL.__str__的执行,打印就不告诉你:
    View Code
  • 相关阅读:
    Flex Charting: Format Your X And Y Axis
    Flex Charting: Format Your Data Tips The Same As Your Axes
    高质量的开源Flex UI组件库项目(FlexLib)
    今天学习Flex3.2嵌入图片,值得说道的是如何嵌入scale9 缩放的图像
    zz[as3 hack技术]垃圾回收机强制执行
    Spark Skinning (including SkinnableComponent) Functional and Design Specification
    Flex DataTransforms类的理解
    关于AS3中弱引用的一点理解
    flex 元字符
    收集整理了一些AS3中常用到的公式
  • 原文地址:https://www.cnblogs.com/Liu-guang-hui/p/9517011.html
Copyright © 2011-2022 走看看