簡體   English   中英

如何與 Python 中的多個類建立關系? 或者如何在另一個 class 中創建 class object?

[英]How to make relation with multiple classes in Python ? or how to create class object in another class?

我在 python 中為后端工作創建了一個 model

這是我的 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'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM