Question on class member in python

Johnny Lee johnnyandfiona at hotmail.com
Tue Oct 18 07:24:01 CEST 2005


Peter Otten 写道:

> Johnny Lee wrote:
>
> > Class A:
> >    def __init__(self):
> >       self.member = 1
> >
> >    def getMember(self):
> >       return self.member
> >
> > a = A()
> >
> > So, is there any difference between a.member and a.getMember? thanks
> > for your help. :)
>
> Yes. accessor methods for simple attributes are a Javaism that should be
> avoided in Python. You can always turn an attribute into a property if the
> need arises to do some calculations behind the scene
>
> >>> class A(object):
> ...     def getMember(self):
> ...             return self.a * self.b
> ...     member = property(getMember)
> ...     def __init__(self):
> ...             self.a = self.b = 42
> ...
> >>> A().member
> 1764
>
> I. e. you are not trapped once you expose a simple attribute.
>
> Peter

Thanks for your help, maybe I should learn how to turn an attibute into
a property first.




More information about the Python-list mailing list