Python 设置对象实例变量的正确方法
我正在编写一个将用户插入数据库的类,在深入之前,我只想确保我的OO方法是干净的:Python 设置对象实例变量的正确方法,python,oop,pylons,Python,Oop,Pylons,我正在编写一个将用户插入数据库的类,在深入之前,我只想确保我的OO方法是干净的: class User(object): def setName(self,name): #Do sanity checks on name self._name = name def setPassword(self,password): #Check password length > 6 characters #Enc
class User(object):
def setName(self,name):
#Do sanity checks on name
self._name = name
def setPassword(self,password):
#Check password length > 6 characters
#Encrypt to md5
self._password = password
def commit(self):
#Commit to database
>>u = User()
>>u.setName('Jason Martinez')
>>u.setPassword('linebreak')
>>u.commit()
这是正确的方法吗?
我应该在上面声明类变量吗?
我是否应该在所有类变量前面使用u,使它们成为私有的
感谢您的帮助。代码中没有类变量,只有实例属性。并使用而不是访问器。并在初始值设定项中创建实例属性,最好使用传入的值:
class User(object):
def __init__(self, name, password='!!'):
self.name = name
self.password = password
...
一般来说是正确的,但是你可以用它来清理
还有一个方便的基于decorator的语法,文档也解释了这一点。使用单个属性不会使您的属性私有:这是一个惯例,告诉您它是一个内部属性,在正常情况下不应该被外部代码访问。对于您的代码,这也意味着密码和名称是只读的 我强烈建议为您的类使用初始化器,它将初始化您的属性,即使是默认值(如None):这将使commit方法更简单,您不必检查_name和_password属性是否存在(使用hasattr)
在代码中使用Pylint 其他人已经指出:如果在获取/设置属性时不需要执行额外的逻辑,请避免使用setter和getter,并使用简单的属性访问。 如果您确实需要额外的逻辑,那么使用属性
如果您有许多参数传递给实例初始化器,请考虑使用单独的对象或字典来保存所有参数:
>>> class User(object):
... def __init__(self, params):
... self.__dict__.update(params)
...
>>> params = {
... 'username': 'john',
... 'password': 'linebreak',
... }
>>> user = User(params)
>>> user.username
'john'
>>> user.password
'linebreak'
另外,在您的情况下,您不需要在类级别声明属性。
如果要在所有类实例中共享相同的值,通常会执行此操作:
>>> class User(object):
... type = 'superuser'
...
>>> user = User()
>>> user2 = User()
>>>
>>> user.type
'superuser'
>>> user2.type
'superuser'
>>>
>>> user2.type = 'instance superuser'
>>>
>>> user.type
'superuser'
>>> user2.type
'instance superuser'
>>> User.type
'superuser'
代码中没有类变量。考虑更新你的标题。你用什么教程来学习Python。这应该包括在内。既然不是,我想知道您使用的是什么教程。“对象实例变量”在PythonThanks中被称为响应的“属性”。我不确定是什么属性,但我会仔细阅读。用户对象有很多变量,大约50个,所以我认为传递到构造函数的变量太多了,不是吗?我知道代码中目前没有类变量。我的意思是,我应该做这些类变量吗?谢谢。当值因实例而异时,永远不要使用类变量。这真的很有帮助。谢谢。我注意到您的构造函数接受了一个必需的
name
参数,因此您使用User()
的示例将抛出一个错误。我编辑了我的示例,将名称
默认为无
,以避免出现这种情况,但您可能希望提供一个完全没有参数的重载实现。
>>> class User(object):
... type = 'superuser'
...
>>> user = User()
>>> user2 = User()
>>>
>>> user.type
'superuser'
>>> user2.type
'superuser'
>>>
>>> user2.type = 'instance superuser'
>>>
>>> user.type
'superuser'
>>> user2.type
'instance superuser'
>>> User.type
'superuser'