我尝试过从file.yml 构建一些类
priters.yml的结构你可以在下面看到:
--- !Station
recipients:
- &first_phone ['Max']
- &second_phone ['Anna', 'Alisa']
obj:
- &first !!python/object:__main__.Nokia
model: Nokia_8800
recipients: *first_phone
- &second !!python/object:__main__.Apple
model: iPhone4
recipients: *second_phone
spam_station: !station
Nokia: *first
Apple: *second
类构造函数出现在spam_station.py 中
from abc import ABC, abstractmethod
from typing import Union
from yaml import YAMLObject, load
class AbstrackPhone(ABC):
@abstractmethod
def send_message(self, message):
pass
class Nokia(AbstrackPhone):
def __init__(self):
self.model = None
self.recipients = []
def send_message(self, message):
for recipient in self.recipients:
print(f"Hi {recipient} i'm {self.model}. {message}")
class Apple(AbstrackPhone):
def __init__(self):
self.model = None
self.recipients = []
def send_message(self, message):
for recipient in self.recipients:
print(f"Hi {recipient} i'm {self.model}. {message}")
class ConstructStation(YAMLObject):
yaml_tag = u'!Station'
@classmethod
def from_yaml(Class, loader, node):
def get_satation(loader, node):
data = loader.construct_mapping(node)
station = Class.Station()
station.add_phones(data.values())
return station
loader.add_constructor(u"!station", get_satation)
return loader.construct_mapping(node)['spam_station']
class Station():
def __init__(self):
self.senders = []
def add_phones(self, phones: Union[list, str]):
self.senders.extend(phones)
def send_message(self, message, **kwargs):
for sender in self.senders:
sender.send_message(message, **kwargs)
def station():
with open('../yaml_config/printers') as file:
spam_station = load(file)
return spam_station
if __name__ == "__main__":
station().send_message('Good luck!!!')
我已尝试在sender.py:中导入并使用"station">
from station.spam_station import station
if __name__ == "__main__":
station().send_message('Good luck!!!')
当我运行spam_station.py时,它是可以的:
Hi Max i'm Nokia_8800. Good luck!!!
Hi Anna i'm iPhone4. Good luck!!!
Hi Alisa i'm iPhone4. Good luck!!!
当我运行sender.py时,我出现了错误:
yaml.constructor.ConstructorError: while constructing a Python object
cannot find 'Nokia' in the module '__main__'
in "../yaml_config/printers", line 7, column 11
如何解决这个问题?请告诉我,将python对象配置为yaml的好方法是什么。谢谢
问题是,当您执行sender.py
时,该文件(而不是spam_station.py
(是__main__
。
最好的解决方案可能是避免依赖于YAML文件中的导入路径。您已经用Station
做到了这一点,所以您也可以简单地在其他类上做到这一点:
class Nokia(AbstrackPhone, YAMLObject):
yaml_tag = u"!Nokia"
def __init__(self, model = None, recipients = []):
self.model = model
self.recipients = recipients
def send_message(self, message):
for recipient in self.recipients:
print(f"Hi {recipient} i'm {self.model}. {message}")
现在可以在YAML文件中使用!Nokia
而不是!!python/object:__main__.Nokia
。Apple
类也是如此。