About the use of **args
Mark McEahern
marklists at mceahern.com
Wed Dec 10 07:37:31 EST 2003
On Wed, 2003-12-10 at 03:24, Graham Ashton wrote:
> [snip]
> I've not run that so it may have syntax errors. It should illustrate the
> principle though; you can use attributes directly until you want to take
> actions when you set them. Then you can make the attribute "private" and
> replace it with a property that access the real attribute, and does
> whatever else you want to do when it's accessed.
A couple of points on Graham's example:
1. You have to subclass from object in order to use property.
2. When Graham nominalizes private, he means that you can still access
the attribute variable directly--and that's by design.
See example below.
Cheers,
// m
#!/usr/bin/env python
class Shoe:
def __init__(self):
self._size = None
def getSize(self):
print "In getSize..."
return self._size
def setSize(self, size):
print "In setSize..."
self._size = size
size = property(getSize, setSize)
class Shoe2(object):
def __init__(self):
self._size = None
def getSize(self):
print "In getSize..."
return self._size
def setSize(self, size):
print "In setSize..."
self._size = size
size = property(getSize, setSize)
s = Shoe()
# Since we haven't subclassed from object, the property descriptor
# doesn't work; notice that setSize() isn't getting called...
s.size = 1
print s.size
# We can still access the "private" member variable. In Python,
# private is merely a convention.
print s._size
# Now that we've subclassed from object, our get/set methods are
# called.
s2 = Shoe2()
s2.size = 1
print s2.size
# And we can still access the "private" member variable.
print s2._size
More information about the Python-list
mailing list