从baseic_servers/config
中倒入vyper
从ent_monitor/config
倒入vyper
问题:从两个不同的项目文件下倒入相同的包,后续调用包内属性的时候会出现冲突/覆盖的问题
此段为rabbitMQ的client端代码,在另一个文件中导用EmailMQClient的时候,会出现一下情况:
import json
import pika
from basic_development.config import C
class EmailMQClient:
# 导入的C作为类属性使用时,调用的是basic_development.config中的C
# routing_key = C.get('basic_service.email.client.routing_key')
# hostname = C.get('basic_service.email.client.hostname')
# exchange = C.get('basic_service.email.client.exchange')
# parameters = pika.ConnectionParameters(host=hostname)
def __init__(self):
# 导入C作为实例属性使用时,调用的室ent_monitor.config中的C
self.routing_key = C.get('basic_service.email.client.routing_key')
self.hostname = C.get('basic_service.email.client.hostname')
self.exchange = C.get('basic_service.email.client.exchange')
self.parameters = pika.ConnectionParameters(host=self.hostname)
def send(self, body: dict):
'''
:param body:{
"receivers":发送给用户
"subject":" ", /主题
"text":" " /内容
"attachments":"list" 附件
}
:return:
'''
# import ipdb;ipdb.sset_trace()
connection = pika.BlockingConnection(self.parameters)
channel = connection.channel()
channel.queue_declare(queue=self.routing_key)
channel.basic_publish(exchange=self.exchange, routing_key=self.routing_key, body=json.dumps(body))
connection.close()
出现以上情况的原因是:
类属性在声明类的同时就被调用,此时ent-monitor/config
还未被调用,所以类属性中的C是basic_development/config
中的C;
实例属性在类实例化的时候才被调用,此时ent-monitor/config
已经被调用,在email.py
模块中调用from basic_development.config import C
的时候,因为命名C,来自from vyper import v as C
,都导的同一个vyper包,所以后调用C的ent-monitor.config
将basic_development/config
中的C覆盖。
总结:
- 导入包的时候注意覆盖问题
- 类属性在声明类的时候就被调用,实例属性只有在类被实例化的时候才会调用