OT: Crazy Programming
Andrew Dalke
dalke at dalkescientific.com
Tue May 14 13:31:37 EDT 2002
Chris:
> Peter Hansen <peter at engcorp.com> wrote:
...
>> Is it just a gut feeling, or do you really have specific examples on
>> which you base these claims?
>
>Well, in writing Perl modules I could continue to use(to access a data
>member of an object, stored as a hash):
..
>And use this as:
>
> print $guy->name("John");
>
>Or, I could try out lvalue subroutines and use something like:
>
..
> print $guy->name="John";
That still follows under "gut feeling" since Python has almost
identical mechanisms, and then some, so your "specific example"
is actually a counter example since there are more ways to do it
in Python. (I could also add __setattribute__ to the mix.)
# NOTE: I consider this to be an ugly style and advise people
# they they shouldn't use it. I write it to make it similar to
# the Perl code.
class Person:
def name(self, name = None):
if name is not None:
self.name = name
return self.name
print guy.name("John")
# This is much more typical Python
class Person:
def __init__(self, name = None):
self.name = name
guy = Person()
guy.name = "John"
print guy.name
# This reimplements the attribute lookup using the older-style
# __getattr__/__setattr__ hooks.
class Person:
def __init__(self, name = None):
self._name = name
def __getattr__(self, key):
if key == "name":
return self._name
return getattr(self, key)
def __setattr__(self, key, value):
if key == "name":
if value == "":
raise TypeError("Name must have at least one letter")
self._name = value
return
self.__dict__[key] = value
guy = Person()
guy.name = "John"
print guy.name
# This is a new (2.2) way to implement attribute lookup
class Person(object):
def _getName(self):
return self._name
def _setName(self, val):
if val == "":
raise TypeError("Name must have at least one letter")
self._name = val
name = property(_getName, _setName)
>>> p = Person()
>>> p.name = "John"
>>> print p.name
John
>>> p.name = ""
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 6, in _setName
TypeError: Name must have at least one letter
>>>
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list