classes: need for an explanation
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Thu Jan 18 07:44:38 EST 2007
On Thu, 18 Jan 2007 03:58:22 -0800, 0k- wrote:
> hello!
>
> i started to write a game in python in which i want to implement
> "dynamically attachable" attributes.
All attributes in Python are dynamically attachable.
>>> class Parrot:
... pass
...
>>> p = Parrot()
>>> hasattr(p, "plumage")
False
>>> p.plumage = "beautiful red"
>>> p.plumage
'beautiful red'
[snip]
> class Thing(object):
> props = {}
> def __init__(self):
> self.props["text"] = TxtAttr("something important")
>
> t1 = Thing()
> t2 = Thing()
>
> t2.props["text"].value = "another string"
Have you considered a simpler class like this?
class Thing(object):
def __init__(self, value="something important"):
self.text = TxtAttr(value)
t2 = Thing("another string")
Then, instead of writing t2.props["text"].value (four lookups) you would
just write t2.text (two lookups).
--
Steve.
More information about the Python-list
mailing list