创建一个Python User()类,它既可以创建新用户,也可以修改现有用户

时间:2010-03-26 08:32:50

标签: python oop

我正在尝试找出创建一个可以在一个中修改和创建新用户的类的最佳方法。这就是我的想法:

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 个答案:

答案 0 :(得分:3)

在我的头顶,我建议如下:

1:在构造函数中为None使用默认参数user_id而不是-1:

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

2:跳过getFullName方法 - 这只是你的Java谈话。而是使用普通的属性访问 - 如果需要,可以稍后将其转换为属性。

答案 1 :(得分:3)

您可以使用元类执行此操作。考虑一下:

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/

答案 2 :(得分:2)

您要实现的目标称为Active Record pattern。我建议学习提供此类事物的现有系统,例如Elixir

答案 3 :(得分:1)

初始化程序的小改动:

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