[CentralOH] Delegate Property

Mark Erbaugh mark at microenh.com
Tue Oct 12 20:29:41 CEST 2010




On Oct 12, 2010, at 1:24 PM, Sam Corder wrote:

> Properties really shouldn't be doing calculations.  It hides the complexity of an object.  Instead you lean toward explicit method invocations with names that imply some work is being done such as calculate_sales_tax.  Conversely if your object is more just a data structure without behavior it would be acceptable to have a sales_tax property where the value was just stored and retrieved.  It is a Single Responsibility Principle (SRP) violation to be both data structure and behavior oriented.
> 
> On Sat, Oct 9, 2010 at 12:38 AM, Mark Erbaugh <mark at microenh.com> wrote:
> Is there a way to delegate a read/write property in a class instance to a read/write property in a different class's instance that is a data member of the class? The only way I can think of is to assign the property getter and setter, but with some ways of creating properties, getters and setters aren't easily gotten.
> 
> i.e.
> 
> class W(object):
>     def a(): #@NoSelf
>         doc = """Docstring""" #@UnusedVariable
>        
>         def fget(self):
>             return self._a
>            
>         def fset(self, value):
>             self._a = value
>            
>         def fdel(self):
>             del self._a
>            
>         return locals()
>        
>     a = property(**a())
> 
>     def __init__(self):
>         self._a = 10
>         
> 
> 
> class B(object):
>     
>     def __init__(self):
>         self.w = W()
> 
> 
>         
> I would like to have an 'a' property on B such that when read they read the a from the contained self.w and when written they write that a.  In this example, the property is just using a local variable, but in a real-world case, the property could be doing some computations.
> 

Sam,

Thanks for the comments. You are correct about the SRP. I think my comment about 'doing some computations' may have been misleading.  In this particular instance the 'computations' are strictly maintaining a persistent copy of the data using SQLAlchemy.  Would that still violate SRP?

My goal was that client code could just access the property (read and write) and not worry about how the value was maintained.  The client can just set the property when it wants to store the value and get the property when it wants to retrieve the value.  The details of the database and persistence are hidden from the client.


Mark
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20101012/337cee87/attachment.html>


More information about the CentralOH mailing list