码迷,mamicode.com
首页 > 编程语言 > 详细

python基础--面向对象之绑定非绑定方法

时间:2019-08-16 23:00:06      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:对象   类的方法   imp   assm   static   time()   md5   需要   结果   

# 类中定义的函数分为两大类,
#一,绑定方法(绑定给谁,谁来调用就自动将它本身当做第一个参数传入)
#   1,绑定到类的方法:用classmethod装饰器装饰的方法。
#       对象也可以掉用,仍将类作为第一个参数传入
#   2,绑定到对象的方法:没有被任何装饰器装饰的方法
#       注意,此时如果类调用对象方法,不会自动传值,需要自己手动传入
#       对象本身。
#   类只有一个,因此对象掉用类方法会自动传值,对象可以有很多个,类调用对象方法
#   时需要传入对象值
class A:
    @classmethod
    def tell_class(cls):
        # 一般绑定到类的方法这样写,不写self,写cls
        print(cls)
    def tell_obj(self):
        print(self)
a = A()
a.tell_class()
a.tell_obj()
A.tell_class()
A.tell_obj(a)
# 二,非绑定方法,用staticmethod装饰器装饰的方法
#   1,不与类和对象绑定,类和对象都可以调用,但是就不会自动传值了
#       就相当于一个普通的函数
#   注意:没有装饰器装饰的方法为绑定到对象的方法
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> #查看结果为普通函数

 

python基础--面向对象之绑定非绑定方法

标签:对象   类的方法   imp   assm   static   time()   md5   需要   结果   

原文地址:https://www.cnblogs.com/cong12586/p/11366535.html

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