Another newbie question
Steven D'Aprano
steve at REMOVEMEcyber.com.au
Thu Dec 8 19:40:41 EST 2005
Paul Rubin wrote:
> Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
>
>>>Yes. Reaching through objects to do things is usually a bad idea.
>>
>>I don't necessarily disagree, but I don't understand why you say this. Why
>>it is bad?
>
>
> The traditional OOP spirit is to encapsulate the object's entire
> behavior in the class definition.
Uh huh. Say I have:
class Coordinate:
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
pt = Coordinate(1.0, 2.5)
Then, somewhere in my application, I need twice the
value of the y ordinate. I would simply say:
value = 2*pt.y
But you claim that this is bad practice, and to be true
to the OOP spirit I should encapsulate the objects
behaviour by creating a method like this:
# add this to the class definition
def mult_y_ord(self, other):
"Return the y ordinate multiplied by other."
return other*self.y
Presumably then I also need add_y_ord, sub_y_ord,
rsub_y_ord, div_y_ord, and so on for every method that
floats understand, plus *another* set of methods that
do the same thing for the x ordinate. And in every
case, these Coordinate methods are trivial one-liners.
Do people really do this?
Yes, I could encapsulate the lot with a factory
function that applied a specified operator to a
specified attribute, and populate the class at runtime.
But why would I want to?
Now, as I see it, the whole point of encapsulation is
that you *don't* need to fill your class definition
with meaningless helper functions. If an attribute of a
instance is a float, you can just call float methods on
the attribute and it should work. If the attribute is a
list, list methods will work. If the attribute is an
instance of a custom class, the same general technique
will still work.
--
Steven.
More information about the Python-list
mailing list