Python__classmethod与staticmethod

本文展示了一个使用Python定义MySQL连接类的例子,并演示了如何通过类方法为每个实例分配一个UUID作为唯一标识。

# 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)
#
# def func1(self):pass
#
#
# conn1=MySql('127.0.0.1',3306)

# print(MySql.from_conf)
# conn2=MySql.from_conf()

# print(conn1.host,conn2.host)

# print(conn1.func1)
# print(conn1.from_conf)
# print(MySql.from_conf)


# conn1.from_conf()
# MySql.from_conf()

 

 

 


import settings
import uuid
class MySql:
def __init__(self,host,port):
self.host=host
self.port=port
self.id=self.create_id()

# @classmethod
# def from_conf(cls): #绑定给类的
# print(cls)
# # return cls(settings.HOST,settings.PORT)
#
# def func1(self): #绑定给对象的
# pass

@staticmethod
def create_id(): #非绑定方法
return str(uuid.uuid1())


conn1=MySql('127.0.0.1',3306)
conn2=MySql('127.0.0.2',3306)
conn3=MySql('127.0.0.3',3306)
# print(MySql.create_id)
# print(conn1.create_id)

print(conn1.id,conn2.id,conn3.id)

 

 

HOST='192.168.31.1'
PORT=3106

 

转载于:https://www.cnblogs.com/wangmengzhu/p/7391434.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值