创建一个类来生成ID

时间:2012-07-12 21:29:54

标签: python class object

我已经阅读了一些有关自动创建对象ID的信息,但仍然迷失了......我试图将以下代码基于Algorias here的优秀示例...

我想要实现的是一个类,它是所有新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

3 个答案:

答案 0 :(得分:0)

这可能是一种类方法。类方法接收类作为第一个参数(不像常规方法那样是类的实例)。这样做你还需要返回值,以便调用者可以访问ie。

class Id_Class(object):    
    new_id   = itertools.count(1000).next
    order_id = itertools.count(1000).next
    person_id= itertools.count(1000).next

    @classmethod
    def new_id(cls, t):   # t = type of id required
        if t == "Order":
            return cls.order_id()
        elif t == "Person":
            return cls.person_id()
        else:
            raise ValueError("Must be 'Order' or 'Person'")

虽然你根本不需要上课:

new_id   = itertools.count(1000).next
order_id = itertools.count(1000).next
person_id= itertools.count(1000).next
def new_id(t):   # t = type of id required
    if t == "Order":
        return order_id()
    elif t == "Person":
        return person_id()

然后可以简单地通过以下方式调用:

my_order_id=new_id('Order')
my_person_id=new_id('Person')

答案 1 :(得分:0)

因为您像静态方法一样调用new_id,所以请尝试添加@staticmethod,如:

class Id_Class(object):    
    new_id   = itertools.count(1000).next
    order_id = itertools.count(1000).next
    person_id= itertools.count(1000).next

    @classmethod
    def new_id(cls, t):   # t = type of id required
        if t == "Order":
            return Id_Class.order_id()
        elif t == "Person":
            return Id_Class.person_id()

答案 2 :(得分:0)

你需要在函数声明中使用@staticmethod装饰器。

class Id_Class(object):    
    new_id   = itertools.count(1000).next
    order_id = itertools.count(1000).next
    person_id= itertools.count(1000).next

    @staticmethod
    def new_id(t):   # t = type of id required
        if t == "Order":
            return Id_Class.order_id()
        elif t == "Person":
            return Id_Class.person_id()