2010-03-26 6 views
1

새로운 사용자를 수정하고 만들 수있는 클래스를 만드는 가장 좋은 방법을 알아 내려고하고 있습니다. 이것이 내가 생각하는 것입니다.새로운 사용자를 생성하고 기존 사용자를 수정하는 Python User() 클래스를 만듭니다.

class User(object): 

    def __init__(self,user_id): 
     if user_id == -1 
      self.new_user = True 
     else: 
      self.new_user = False 

      #fetch all records from db about user_id 
      self._populateUser() 

    def commit(self): 
     if self.new_user: 
      #Do INSERTs 
     else: 
      #Do UPDATEs 

    def delete(self): 
     if self.new_user == False: 
      return False 

     #Delete user code here 

    def _populate(self): 
     #Query self.user_id from database and 
     #set all instance variables, e.g. 
     #self.name = row['name'] 

    def getFullName(self): 
     return self.name 

#Create a new user 
>>u = User() 
>>u.name = 'Jason Martinez' 
>>u.password = 'linebreak' 
>>u.commit() 
>>print u.getFullName() 
>>Jason Martinez 

#Update existing user 
>>u = User(43) 
>>u.name = 'New Name Here' 
>>u.commit() 
>>print u.getFullName() 
>>New Name Here 

이렇게하는 것이 논리적이고 깨끗한 방법입니까? 더 좋은 방법이 있습니까?

감사합니다.

+1

가 수행 한 후') (커밋'에서 True로'self.new_user'을 설정해야합니다

class MetaCity: def __call__(cls,name): “”“ If it’s in the database, retrieve it and return it If it’s not there, create it and return it ““” theCity = database.get(name) # your custom code to get the object from the db goes here if not theCity: # create a new one theCity = type.__call__(cls,name) return theCity class City(): __metaclass__ = MetaCity name = Field(Unicode(64)) 

이제 당신은 같은 일을 할 수있다 삽입이 성공적으로 이루어지면 같은 객체에서'commit()'을 두 번 호출하면 문제가 생길 수 있습니다. –

답변

2

내 머리 위로 떨어져, 나는 제안 다음

1 : 생성자에서 user_id에 대한 기본 인수 None 대신에 -1을 사용하여 :

def __init__(self, user_id=None): 
    if user_id is None: 
     ... 

2 : 건너 뛰기는 getFullName입니다. 바로 자바 토크입니다. 대신에 일반 속성 액세스를 사용하십시오. 필요할 경우 나중에 속성으로 변환 할 수 있습니다.

1

당신의 초기화에 작은 변화 :

def __init__(self, user_id=None): 
     if user_id is None: 
+0

감사. 그래서 다른 모든 것들이 좋아 보인다 :)? – ensnare

+1

그리고 다른 대답에서 준 "접근자를 사용하지 마십시오". –

관련 문제