0

我已经阅读了一些关于自动创建对象 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
4

3 回答 3

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')
于 2012-07-12T21:33:23.083 回答
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()
于 2012-07-12T21:34:11.427 回答
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()
于 2012-07-12T21:34:22.770 回答