创建一个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
这样做合理吗?有没有更好的方法呢?
谢谢。
4 个回答
4
你可以通过元类来实现这个功能。想象一下:
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.
3
我想到的建议如下:
1: 在构造函数中,把 user_id
的默认值设置为 None
,而不是 -1:
def __init__(self, user_id=None):
if user_id is None:
...
2: 可以省略 getFullName
这个方法——这只是你在用 Java 的习惯。可以直接使用普通的属性访问,如果以后需要的话,再把它改成属性也可以。