A newbie question about class

Tim Legant tim-dated-1013908624.48bcde at catseye.net
Sun Feb 10 02:17:03 CET 2002


newgene at bigfoot.com (newgene) writes:

> Hi, group,
>      I have a newbie question about building a class:
> 
> eg.
> 
> class A:
>    def __init__(self,x=None):
>        self.x=x
>        if self.x != None:
>             self.y=x**2
>        else:
>             self.y=x**2
> 
> If I initialize A like "a=A(2)", then I can get "a.y=4" automatically;
> but if I initialize A like "a=A()", then when I give "a.x=2" later, I
> can not get the value of "a.y" like the former. Of course I can use a
> method to set the value of "a.y", but is there a machanism to get the
> "a.y" automatically whenever I change the value of "a.x"?

A comment and a suggested answer....  First, your else does exactly
the same thing as your if.  Unfortunately it will blow up, since you
can't raise None to any power!  I will assume it's a cut-and-paste-o.

Instead of twiddling your class's bits from outside the class

a.x = 2

consider creating a set_x function:

class A:
    def __init__(self, x=None):
        self.set_x(x)

    def set_x(self, x)
        self.x = x
        if self.x:
            self.y = x**2

Now a = A(2) still sets a.x to 2 and a.y to 4.  a = A() sets a.x to
None and doesn't set a.y.  Finally, from outside the class you just
call a.set_x(3).  a.x will be set to 3 and a.y will be set to 9.


Tim




More information about the Python-list mailing list