2012-07-12 2 views
0

개체 ID 생성 자동화에 대해 읽었지만 여전히 잃어 버렸습니다 ... Algorias here의 위대한 예제를 중심으로 다음 코드를 기반으로했습니다.ID를 생성하는 클래스 만들기

나는 모든 새로운 ID 요청을위한 리소스 클래스입니다. 논리는 한 곳에서하는 경우가 ...

을 쉽게 관리 할 수 ​​있어야한다는 것입니다하지만 난 주문의 인스턴스에 X를 설정에 도착했을 때 나는 다음과 같은 얻을 :

>>> 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 

답변

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() 
+0

여전히 '없음'(분명히 의도하지 않은)을 반환하며 1 개의 인수만으로 호출되므로 잘못된 인수 번호로 호출되었으므로 예외가 발생합니다. – mgilson

+0

Eric의 코드를 사용하는 경우에는 자신에게 id를 할당하지 말고 주문의 uid에 할당하므로 직접 반환하십시오. – Marconi

+0

@Marconi - 또한'self' 매개 변수를 없애십시오 ... – mgilson

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') 
+0

그래서 나는 그것을 다음과 같이 호출 할 필요가 없습니다. Id_Class.new_id ('Order')? 하, 방금 시도하고 내 자신의 질문에 대답 :) – AtomicCrash

+0

@ user1386172 클래스를 사용하여 장점은 당신의 네임 스페이스를 약간 더 명확하게 유지됩니다 -하지만 당신은 변수 이름'order_id'을'_order_id'로 변경할 수 있으며 아마 충분 해. – mgilson

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() 
+0

'cls'를 사용하지 않으려한다면 왜 classmethod로 만드시겠습니까? 마찬가지로 정적 메소드로 만들고'cls' 인수를 제거 할 수 있습니다. – mgilson

관련 문제