Making every no-arg method a property?
Steven D'Aprano
steve at pearwood.info
Wed Aug 6 05:15:32 EDT 2014
On Wed, 06 Aug 2014 12:07:58 +1000, Chris Angelico wrote:
> On Wed, Aug 6, 2014 at 10:49 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> A
>> plethora of argument-less methods is a code smell -- that doesn't mean
>> it's *necessarily* a bad idea, but the class design really needs a
>> careful review.
>
> There are plenty of no-argument mutator methods, where the name of the
> method (and the target object, obviously) is all the info you need. You
> can clear() or copy() something with any more info, reverse() a list,
> pop() from a list, etc.
They don't have to be mutator methods. The same applies to string methods
like upper(), lower(), isalpha() and many others.
I'm not sure if you're agreeing or disagreeing with me. All these
examples shouldn't be treated as properties either. This should be
grounds for being slapped with a large herring:
mydict.clear # returns None, operates by side-effect
Some things are conceptually either methods or attributes:
mydict.keys # could be okay I suppose
but I digress. As I said, zero-argument (one-argument, if you count self)
methods are a code smell, not an error. As is so often the case in
programming, the fundamental sin here is *coupling* -- zero-argument
methods are bad if they require coupling to temporary attributes which
exist only to communicate an argument to the method.
In other words, one of the sins of zero-argument methods is the same as
that of zero-argument functions. We wouldn't write this:
def double():
return number_to_operate_on*2
number_to_operate_on = 23
print double()
number_to_operate_on = 42
print double()
Turning it into a method on an instance, and turning the global into a
"per instance global" (instead of per module, or application-wide)
doesn't make it any better.
--
Steven
More information about the Python-list
mailing list