Reputation: 7857
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?
Upvotes: 0
Views: 456
Reputation: 49048
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:
class Person:
pass
x = Person
x.name = "test"
print x.name
If you do need to do something special in the getter or setter, like a SQL query, try this:
class Person(object):
def __init__(self):
self._name = None
self._name_changed = False
@property
def name(self):
if not self._name:
self._name = 'select sql query'
return self._name
@name.setter
def name(self, value):
self._name = value
self._name_changed = True
def save(self):
if self._name_changed:
print 'update sql query set name=' + self._name
self._name_changed = False
x = Person()
x.name = 'test'
print x.name
x.save()
Upvotes: 1
Reputation: 43024
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.
Upvotes: 1
Reputation: 69192
Python properties are designed to resolve this issue.
Properties allow the phases blah.name
, blah.name = x
, and del blah.name
to automatically invoke getter, setter, and deleter methods, if such methods have been defined.
Upvotes: 5