我與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個不同的文件中以提高可讀性時,這一直在工作。我輸入的對象是否錯誤?
請查看https://docs.python.org/2/library/functions.html#isinstance 或https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertIsInstance for斷言 – Busturdust