2015-12-01 86 views
0

我與Python玩,但我沒有得到遺產的權利Python的繼承父母的孩子不等於型

在我的包我有User.py

class User(object): 
    """This is the base user 
    This is where all the dirty stuff happens 
    """ 
    def __init__(self, mail=None, password=None): 
    self._build({"mail": mail, "password": password, "fields": dict({})}) 

    def _build(self, props): 
    """Private method for building objects based on dicts 
    """ 
    props["uuid"] = uuid.uuid4() 

    for k, v in props.iteritems(): 
     setattr(self, k, v) 

    @staticmethod 
    def get_or_create(**kwargs): 
    """This method fetches a matching User 
     or creates on based on email and password 
    """ 
    db = utils.get_client().users 

    if kwargs.get("mail") is None: 
     raise ValueError("%s.mail cannot be None" % self.__class__.__name__) 

    cursor = db.users.find_one({"mail": kwargs.get("mail", None)}) 

    if cursor is None: 
     user = User() 
     user._build({"mail": kwargs.get("mail", None), "password": kwargs.get("password", None)}) 
     user.save() 
    else: 
     if cursor.get("_type") == "Customer": 
     user = Customer() 
     else: 
     user = User() 

     user._build(cursor) 

    return user 

後來才知​​道有Customer.py繼承用戶

from gearbroker.user import User 

class Customer(User): 

    def __init__(self, **kwargs): 
      User.__init__(self, mail=kwargs.get("mail", None), password=kwargs.get("password", None)) 

兩者都位於根級別的相同包中。我的測試使我這個

AssertionError: <class 'mypackage.user.Customer'> != <class 'mypackage.customer.Customer'> 

當我運行這個測試

customer = Customer(mail="[email protected]", password="foobar") 
    customer.save() 

    user = User.get_or_create(mail="[email protected]", password="foobar") 

    assert_equal(type(user), type(Customer())) 

在這個測試文件導入我喜歡這個

from gearbroker.user import User 
from gearbroker.customer import Customer 

我如何去了解這個物體?客戶應該是User類的孩子,在比較他們的類型時,他們都應該是用戶。直到我決定將客戶和用戶類移到2個不同的文件中以提高可讀性時,這一直在工作。我輸入的對象是否錯誤?

+0

請查看https://docs.python.org/2/library/functions.html#isinstance 或https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertIsInstance for斷言 – Busturdust

回答

0

這聽起來像你有兩個不同的定義,Customer類。你的測試似乎表明你正在混淆他們。

我懷疑你的錯誤歸結爲是,你想指不合格名稱User,並在所有的模塊Customer,你正在使用某種from module import Name語法來得到它。當你有循環依賴時(user模塊需要訪問Customer類,但customer模塊需要訪問User類)。

要解決此問題,我建議使用常規import module語句並將不合格的類名更改爲合格版本(user.Usercustomer.Customer)。

或者,只要保持你的類都在同一模塊! Python不像Java,每個類定義都需要在自己的文件中。如果您的UserCustomer類彼此緊密相連,務必將它們保持在同一模塊中!

+0

如果我將導入更改爲導入齒輪經銷商而不是導入gearbroker.user和gearbroker.customer,它應該起作用嗎? –

+0

測試中的進口不是重要的,而是'user'和'customer'模塊中的進口。無論出於何種原因,'user'模塊中看到的'Customer'類與'customer'模塊中找到的類不是同一類。既然你沒有顯示那些導入,我不能具體說出什麼是錯誤的,或者你可以做些什麼來解決問題。 – Blckknght

+0

在客戶中添加了用戶導入 –