推荐的“设计模式”是什么?通过类变量公开数据?
我见过很多模块允许人们使用以下方式访问数据:
print blah.name
与以下方式相反:
print blah.get_name()
鉴于名称是静态变量,使用变量方法而不是调用函数似乎是更好的选择。
我想知道自己实现这一点的最佳“设计”是什么。例如,给定一个 Person
对象,我应该如何公开 name
和 age
?
class Person:
def __init__(self, id):
self.name = self.get_name(id)
self.age = self.get_age(id)
def get_name(self, id=None):
if not id:
return self.name
else:
# sql query to get the name
这将使我能够:
x = Person
print x.name
有推荐的替代方案吗?
I've seen quite a few modules allow people to access data using:
print blah.name
As opposed to:
print blah.get_name()
Given the name is a a static variable, it seems like a better choice to use the variable method rather than calling a function.
I'm wondering what the best 'design' is for implementing this myself. For example, given a Person
object, how should I expose the name
and age
?
class Person:
def __init__(self, id):
self.name = self.get_name(id)
self.age = self.get_age(id)
def get_name(self, id=None):
if not id:
return self.name
else:
# sql query to get the name
This would allow me to:
x = Person
print x.name
Is there a recommended alternative?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Python 属性 旨在解决此问题。
属性允许阶段
blah.name
、blah.name = x
和del blah.name
自动调用getter、setter和deleter方法,如果已经定义了这样的方法。Python properties are designed to resolve this issue.
Properties allow the phases
blah.name
,blah.name = x
, anddel blah.name
to automatically invoke getter, setter, and deleter methods, if such methods have been defined.根据您的示例,您可能需要查看 sqlalchemy 及其 ORM。它为你做了很多这样的工作。它已经将列映射为对象属性。
Given your example you might want to take a look at sqlalchemy and its ORM. It does a lot of that work for you. It already maps columns as object attributes.
我可能误解了你的问题,但我认为你想太多了。除非您需要在 getter 或 setter 中做一些特殊的事情,否则不需要声明属性。您只需在需要时开始使用它们,如下所示:
如果您确实需要在 getter 或 setter 中执行一些特殊操作(例如 SQL 查询),请尝试以下操作:
I may be misunderstanding your question, but I think you're overthinking it. Unless you need to do something special in the getter or setter, the attributes don't need to be declared. You just start using them when you need them, like this:
If you do need to do something special in the getter or setter, like a SQL query, try this: