Создайте класс Python User (), который одновременно создает новых пользователей и изменяет существующих - PullRequest
2 голосов
/ 26 марта 2010

Я пытаюсь найти лучший способ создать класс, который может изменять и создавать новых пользователей в одном.Вот о чем я думаю:

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

Это логичный и чистый способ сделать это?Есть ли лучший способ?

Спасибо.

Ответы [ 4 ]

3 голосов
/ 17 мая 2010

Вы можете сделать это с метаклассами. Учтите это:

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

Теперь вы можете делать такие вещи, как:

paris = City(name=u"Paris") # this will create the Paris City in the database and return it.
paris_again = City(name=u"Paris") # this will retrieve Paris from the database and return it.

от: http://yassinechaouche.thecoderblogs.com/2009/11/21/using-beaker-as-a-second-level-query-cache-for-sqlalchemy-in-pylons/

3 голосов
/ 26 марта 2010

С макушки головы я бы предложил следующее:

1: использовать аргумент по умолчанию None вместо -1 для user_id в конструкторе:

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

2: пропустите метод getFullName - это просто ваш разговор по Java. Вместо этого используйте обычный атрибут доступа - вы можете преобразовать его в свойство позже, если вам нужно.

2 голосов
/ 26 марта 2010

То, что вы пытаетесь достичь, называется Шаблон активной записи . Я предлагаю изучить существующие системы, предоставляющие такие вещи, как Elixir .

1 голос
/ 26 марта 2010

Небольшое изменение вашего инициализатора:

def __init__(self, user_id=None):
      if user_id is None:
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...