我在python中为后端工作创建了一个模型
这是我的python代码
class User:
def __init__(self, _id=None):
self._id = _id
if self._id is not None:
self.contact = Contact()
self.contact.user_id = self._id
class Contact:
def __init__(self, _id=None):
self._id = _id
self.user_id = None
if self._id is not None:
self.vehicle = Vehicle()
self.vehicle.contact_id = self._id
class Vehicle:
def __init__(self, _id=None):
self._id = _id
self.contact_id = None
self.user_id = None
def create_company(self, company_name):
# check if user id is set
if None in (self.contact_id, self.user_id):
return {'result': False, 'msg': 'user or contact id is not set'}
# here i will use user id and contact id
return {'result': True, 'msg' : 'ok'}
我想创建一个链接到用户id和联系人id 的汽车公司
我想这样做
User('user_id').Contact('contact_id').vehicle.create_company('any name')
但我遇到了一个错误,我知道为什么,但不知道如何实现解决方案
我得到错误
AttributeError: 'User' object has no attribute 'Contact'
不知怎么的,我通过这段代码实现了,请建议更好的方法。
class User:
def __init__(self, _id=None):
self._id = _id
def Contact(self, _id):
if self._id is None:
raise Exception({'result':False, 'msg': 'user id is not set'})
self.contact = Contact(_id)
self.contact.user_id = self._id
class Contact:
def __init__(self, _id=None):
self._id = _id
def Vehicle(self):
if self._id is None:
raise Exception({'result': False, 'msg': 'contact id is not set'})
self.vehicle = Vehicle()
self.vehicle.contact_id = self._id
if hasattr(self, 'user_id'):
self.vehicle.user_id = self.user_id
class Vehicle:
def __init__(self, _id=None):
self._id = _id
def create_company(self, company_name=None):
# check if user id is set
if not hasattr(self, 'user_id') or not hasattr(self, 'contact_id'):
return {'result': False}
# here i will use user id and contact id
return {'result': True, 'msg' : 'ok'}
并像这个一样使用它
test = User('admin')
test.Contact('person')
test.contact.Vehicle()
print(test.contact.vehicle.create_company())
结果就是我想要的
{'result': True, 'msg': 'ok'}