简体   繁体   中英

What's the recommended 'design pattern' for exposing data via class variables?

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 aa 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?

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.

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM