zoukankan      html  css  js  c++  java
  • 绑定方法与非绑定方法

    一:绑定方法

    绑定给谁,谁来调用就自动将它本身当作第一个参数自动传入。

    1.1 类的绑定方法:

    是用classmethod装饰器装饰的方法。
    -由类来调用,会将类当做第一个参数传入。

    classmethod:
    是一个装饰器,给在类内部定义方法中装饰,将类内部的方法变为 “类的绑定方法”

    2.1 对象的绑定方法

    没有被任何装饰器装饰的方法。
    -由对象来调用,会将对象当做第一个参数传入

    二、非绑定方法(静态方法)

    是用staticmethod装饰器装饰的方法,给在类内部定义方法中装饰,将类内部的方法变为 “非绑定方法”。
    
    可以由对象或类来调用,谁来调用都是一个普通方法(普通函数),方法需要传入几个参数,就得传入几个。
    
    注意:与绑定到对象方法区分开,在类中直接定义的函数,没有被任何装饰器装饰的,都是绑定到对象的方法,可不是普通函数,对象调用该方法会自动传值,而staticmethod装饰的方法,不管谁来调用,都没有自动传值一说
    class Foo:
        @staticmethod
        def func(res):
            print(res)
    
    obj = Foo()
    
    # 对象调用非绑定方法
    obj.func(123)
    
    # 类调用非绑定方法
    Foo.func(1234)
    绑定方法:
    
    > 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):  #cls ---> MYSQL
            return cls(settings.HOST,settings.PORT)  #cls调用的时候自动触发__init__,
    
    print(MySQL.from_conf) #<bound method MySQL.from_conf of <class '__main__.MySQL'>>
    conn=MySQL.from_conf()
    print(conn.host,conn.port)  # 127.0.0.1   3306
    
    # conn.from_conf() #对象也可以调用,但是默认传的第一个参数仍然是类
  • 相关阅读:
    Distinctive Image Features from ScaleInvariant
    Natural Language Toolkit
    Regression analysis
    泌尿系统 Excretory system
    file_get_contents preg_match php nameisboy
    wWAITING
    instructionset architecture Processor Architecture
    improve performance whilemaintaining the functionality of a simpler and more abstract model design of processor hardware
    cluster analysis in data mining
    Maximum Likelihood
  • 原文地址:https://www.cnblogs.com/wddxx/p/13671141.html
Copyright © 2011-2022 走看看