[Tutor] Class Construction question [C++ and Python class introduction]

Yigal Duppen yduppen@xs4all.nl
Wed Nov 13 08:39:02 2002


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> It's often claimed that all attributes should be at least protected,
> and only accessed through set or get methods. With this assumption,
> it's obviously logical to do as Danny wrote above.
>
> In Python this isn't really such a big issue though, because of
> the magic methods __setattr__ and __getattr__. They can override
> attribute modification and access. This means that if you change
> your mind, and for instance calculate a value on the fly instead
> of storing it, you can handle that change even if there is code
>
Even better, (something I realised only recently), as of Python2.2 you ca=
n=20
also change a normal attribute to a property! No more fidgeting with the=20
(quite dangerous IMHO) __getattr__ and __setattr__.=20

PRE:

class C:
=09
=09def __init__(self):
=09=09self.a =3D 10


c =3D C()
print c.a



POST:

class C(object):

=09def __init__(self):
=09=09self.a =3D 10

=09def setA(self, a):
=09=09self._a =3D a
=09
=09def getA(self):
=09=09return self._a

=09a =3D property(getA, setA, None, "a is now a property!!")

c =3D C()
print c.a
# which automatically becomes: c.getA()


YDD
- --=20
http://www.xs4all.nl/~yduppen
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE90lXKLsKMuCf5EdwRAi+cAKDvDgXPQxcNHLBT+RV65TGffNT4VACfYXBS
YYOGAGmNGMPdCvh36CdiJ/c=3D
=3D4zPe
-----END PGP SIGNATURE-----