3.2

定义MySQL类
要求:
1.对象有id、host、port三个属性
2.定义工具create_id,在实例化时为每个对象随机生成id,保证id唯一
3.提供两种实例化方式,方式一:用户传入host和port 方式二:从配置文件中读取host和port进行实例化
 1 import hashlib
 2 import string
 3 import random
 4 import settings
 5 
 6 class MySql:
 7     def __init__(self,host,port):
 8         self.id=self.create_id()
 9         self.host=host
10         self.port=port
11 
12     @classmethod
13     def from_conf(cls):
14         obj=cls(
15             settings.host,
16             settings.post
17         )
18         return obj
19 
20     @staticmethod
21     def create_id():
22         m=hashlib.md5(''.join(random.sample(string.digits+string.ascii_letters+string.punctuation,8)).encode('utf-8'))
23         return m.hexdigest()
24 
25 
26 mysql=MySql('127.0.0.1',8086)
27 print(mysql.__dict__)
28 obj1=MySql.from_conf()
29 print(obj1.__dict__)
settings:文件
host='168.100.100.123'
post=8089
原文地址:https://www.cnblogs.com/alice-bj/p/8552293.html