码迷,mamicode.com
首页 > 其他好文 > 详细

绑定方法与非绑定方法

时间:2018-06-06 15:57:57      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:面向对象   pycha   查看   settings   工具   规则   port   path   enc   

类的绑定方法

一:绑定方法(绑定给谁,就应该由谁来调用,谁来调用就回把调用者当作第一个参数自动传入):

  • 绑定给对象的方法:在类内定义的没有被任何装饰器修饰的
  为对象量身定制

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

  (属于类的函数,类可以调用,但是必须按照函数的规则来,没有自动传值那么一说)
  • 绑定给类的方法:在类内定义的被装饰器classmethod修饰的方法
#settings.py
HOST=‘127.0.0.1‘
PORT=3306
DB_PATH=r‘C:\Users\Administrator\PycharmProjects\test\面向对象编程\test1\db‘

#test.py
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() #对象也可以调用,但是默认传的第一个参数仍然是类

二、非绑定方法:没有自动传值这么一说了,就类中定义的一个普通工具,对象和类都可以使用

  • 非绑定方法:不与类或者对象绑定,用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> #查看结果为普通函数

绑定方法与非绑定方法

标签:面向对象   pycha   查看   settings   工具   规则   port   path   enc   

原文地址:https://www.cnblogs.com/yjiu1990/p/9144516.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!