制作可在 lambda 中使用的属性的最 Pythonic 方法是什么?
更具体地说,我希望能够支持 lambda:
在下面的示例中,假设已全局声明了一个名为 spam_button
的按钮小部件。还假设 Eggs
类将至少有 10 个属性,并且需要以相同的方式访问所有属性(我喜欢一致性)。
我可以做到这一点的第一种可能的方法是仅使用 getter 和 setter:
class Eggs(object):
def __init__(self):
self._spam = ''
self.set_spam('Monster')
print self.get_spam()
spam_button.bind('<Enter>', lambda: self.set_spam('Ouch'))
def set_spam(self, spam):
if len(spam) <= 32:
self._spam = spam
def get_spam(self):
return self._spam
但是如果我使用此方法并且有很多属性,则代码可能会太长而难以管理。
第二种方法是使用属性,并在回调中使用 setter:
class Eggs(object):
def __init__(self):
self._spam = ''
self.spam = 'Monster'
print self.spam
spam_button.bind('<Enter>', lambda: self.set_spam('Ouch'))
def set_spam(self, spam):
if len(spam) <= 32:
self._spam = spam
def get_spam(self):
return self._spam
spam = property(get_spam, set_spam)
这种方法在直接访问属性时比第一种方法简单一些,但在使用 lambda 时却不一致。
第三种方法是使用 get 和 set 方法创建一个附加类:
class Spam(object):
def __init__(self):
self._value = ''
def set(self, value):
if len(spam) <= 32:
self._value = value
def get(self):
return self._value
class Eggs(object):
def __init__(self):
self._spam = ''
self.spam = Spam()
self.spam.set('Monster')
print self.spam.get()
spam_button.bind('<Enter>', lambda: self.spam.set('Ouch'))
此方法比第一种方法更有组织性,但我需要为每种类型的验证创建一个类。
我可能做到的最后一种方法是使用方法而不是属性(属性是第二个示例):
class Eggs(object):
def __init__(self):
self._spam = ''
self.spam('Monster')
print self.spam()
spam_button.bind('<Enter>', lambda: self.spam('Ouch'))
def spam(self, spam=None):
if spam != None:
if len(spam) <= 32:
self._spam = spam
else:
return self._spam
此方法可能是最短的,但很难一眼看出我是在获取还是在设置。
这些方法中哪一个(如果有)是首选?
More specifically, I want to be able to support lambda: <some_or_other_setter>
, but I want to keep the code clear and to a concise. I have to validate the value, so I need a setter of some kind. I need to use lambda because I need to pass callbacks to Tkinter events. I also need to be able to modify the value of the attribute outside a binding.
In my following examples, assume that a button widget called spam_button
has been declared globally. Also asume that the class Eggs
will have at least 10 attributes than need to all be accessed the same way (I like consistency).
The first possible way I could do this is using just getters and setters:
class Eggs(object):
def __init__(self):
self._spam = ''
self.set_spam('Monster')
print self.get_spam()
spam_button.bind('<Enter>', lambda: self.set_spam('Ouch'))
def set_spam(self, spam):
if len(spam) <= 32:
self._spam = spam
def get_spam(self):
return self._spam
But if I use this method and have lots of attributes, the code may get too long to manage.
The second way I could do this is use properties, and use the setter in the callback:
class Eggs(object):
def __init__(self):
self._spam = ''
self.spam = 'Monster'
print self.spam
spam_button.bind('<Enter>', lambda: self.set_spam('Ouch'))
def set_spam(self, spam):
if len(spam) <= 32:
self._spam = spam
def get_spam(self):
return self._spam
spam = property(get_spam, set_spam)
This way is a bit simpler than the first when accessing the attribute directly, but is inconsistent when using lambda.
The third way to do this would be to make an additional class with get and set methods:
class Spam(object):
def __init__(self):
self._value = ''
def set(self, value):
if len(spam) <= 32:
self._value = value
def get(self):
return self._value
class Eggs(object):
def __init__(self):
self._spam = ''
self.spam = Spam()
self.spam.set('Monster')
print self.spam.get()
spam_button.bind('<Enter>', lambda: self.spam.set('Ouch'))
This method is more organised than the first, but I will need to make a class for each type of validation.
The last way I might do it is use methods instead of properties (properties were the second example):
class Eggs(object):
def __init__(self):
self._spam = ''
self.spam('Monster')
print self.spam()
spam_button.bind('<Enter>', lambda: self.spam('Ouch'))
def spam(self, spam=None):
if spam != None:
if len(spam) <= 32:
self._spam = spam
else:
return self._spam
This method will probably be the shortest, but it is harder at a glance to tell whether I am getting or setting.
Which (if any) of these methods are preferred?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用闭包返回一个用作回调的函数,并将每个条件定义为一个函数(使用
lambda
或def
,您的偏好) 而不是将每个 setter 作为函数。编辑:现在您可以从任何地方调用设置器,它将检查条件。
编辑2:这样,setter 将检查它是否收到事件,如果没有,则使用它传递的值。您还可以使用:
Use a closure to return a function to be used as a callback, and define each condition as a function (using
lambda
ordef
, your preference) instead of each setter as a function.Edit: Now you can call the setter, which will check the condition, from anywhere.
Edit 2: This way, the setter will check if it got an event, and if not, use the value it's passed. You could also use:
我仍然建议使用字典,然后就到此为止了。将其子类化并重写
__setitem__
来进行数据验证,然后不用担心 getter:I still suggest using a dict and calling it a day. Subclass it and override
__setitem__
to do your data validation, then don't worry about getters:验证问题可以使用
属性
来处理:显然,您仍然可以使用
self._spam = 'spam '*10+'baked beans and spam'
而不受惩罚。使用内置的
setattr
:如果您反对
..."spam"...
并且更喜欢...spam...
,您可以使用property
的方法:或者,因为
property
是一个描述符:但出于明显的原因,我希望第一个版本是首选。
The validation issue can be handled using a
property
:Obviously, you can still use
self._spam = 'spam '*10+'baked beans and spam'
with impunity.Use the builtin
setattr
:If you object to
..."spam"...
and prefer just...spam...
, you can use methods ofproperty
:or, since
property
is a descriptor:But the first version is preferred, I hope for obvious reasons.
我喜欢基于类的方法。您可能需要进行一组有限的验证(例如字符串的最大长度、数字的有效范围等),因此您将拥有有限数量的类。
例如:
如果您确实需要对不同的属性进行独特的验证,那么您就无法避免编写大量代码。但正如编程中一贯的那样,当您开始重复自己时,请进行概括。
TokenMacGuy 建议后更新:使用相当未知的 Python 功能“描述符”的替代方案:
我发现了 对描述符非常好的介绍。
I like the class-based approach. You'll probably have a limited set of validation that you want to do (for example maximum length of a string, valid range for a number, etc.), so you'll have a limited number of classes.
For example:
If you really have unique validations that need to be done to the different attributes, you can't get away from writing a lot of code. But as always in programming, generalize when you start repeating yourself.
Update after suggestion by TokenMacGuy: Alternative using the fairly unknown Python feature "descriptors":
I found a pretty good introduction to descriptors.