我已经阅读了一些关于自动创建对象 ID 的内容,但仍然迷路了......我试图将以下代码基于 Algorias在这里的伟大示例......
我想要实现的是一个类,它是所有新 id 请求的资源。逻辑是,如果它都在一个地方,它应该更容易管理......
但是当我将 x 设置为 Order 的一个实例时,我得到以下信息:
>>> x = Order()
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
x = Order()
File "C:\Python27\delete.py", line 17, in __init__
self.uid = Id_Class.new_id("Order")
TypeError: unbound method new_id() must be called with Id_Class instance as first argument (got str instance instead)
任何帮助将不胜感激
import itertools
class Id_Class(object):
new_id = itertools.count(1000).next
order_id = itertools.count(1000).next
person_id= itertools.count(1000).next
def new_id(self, t): # t = type of id required
if t == "Order":
self.id = Id_Class.order_id()
elif t == "Person":
self.id = Id_Class.person_id()
class Order(object):
def __init__(self):
self.uid = Id_Class.new_id("Order")
self.cus='Test'
class Person(object):
pass