gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:11:40 25 4
gpt4 key购买 nike

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

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

这是一种合乎逻辑且简洁的方法吗?有没有更好的办法?

谢谢。

最佳答案

您可以使用元类来做到这一点。考虑一下:

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/

关于python - 创建一个 Python User() 类,它既可以创建新用户又可以修改现有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2521907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com