HELP : class and variables

Discussion in 'Python' started by vincent delft, Sep 1, 2003.

  1. Sorry if my question is stupid.
    I've missed something with classes.
    Can you explain the following ?
    class test:
    var1=1
    var2=2
    res=var1+var2

    t=test()
    print t.res
    >> 3

    t.var1=6
    print t.res
    >> 3


    ??????????????????
    I though that everithing is memory zones.
    Why it's not 8 ?

    Thanks
    vincent delft, Sep 1, 2003
    #1
    1. Advertising

  2. vincent delft wrote:
    > Sorry if my question is stupid.
    > I've missed something with classes.
    > Can you explain the following ?
    > class test:
    > var1=1
    > var2=2
    > res=var1+var2
    >
    > t=test()
    > print t.res
    >
    >>>3


    Until here, t.var1 means test.var1 (class variable)

    > t.var1=6


    From here, you created a new instance variable for object t, named
    var1. It hides test.var1.

    > print t.res
    >
    >>>3


    What would you expect ?
    1/ assigning to t.var1 does not modify test.var1
    2/ modifiying test.var1 would not modify test.res anyway ! Guess why ?


    Try this instead :
    >>> class test:

    .... def __init__(self):
    .... # create instance variables
    .... self.var1 = 1
    .... self.var2 = 2
    .... def res(self):
    .... return self.var1 + self.var2
    ....
    >>> t = test()
    >>> t.res()

    3
    >>> t.var1 = 6
    >>> t.res()

    8

    Bruno
    Bruno Desthuilliers, Sep 1, 2003
    #2
    1. Advertising

  3. vincent delft skrev:

    >Can you explain the following ?


    Yes.

    >class test:
    > var1=1
    > var2=2
    > res=var1+var2


    >t=test()
    >print t.res
    >>> 3


    >t.var1=6
    >print t.res
    >>> 3


    Changing var1 does not change res.

    You might like to make it a function instead:

    class Test:
    var1=1
    var2=2
    def res (self):
    return self.var1+self.var2

    t=Test()
    t.var1=6
    print t.res()

    I learned in Java to give classes names with the first letter
    capitalized. I find that a useful convention.

    --
    Bertel, Denmark
    Bertel Lund Hansen, Sep 1, 2003
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. avnrao
    Replies:
    0
    Views:
    3,349
    avnrao
    May 7, 2004
  2. Replies:
    10
    Views:
    35,843
    jporter892
    Jun 6, 2011
  3. E11
    Replies:
    1
    Views:
    4,711
    Thomas Weidenfeller
    Oct 12, 2005
  4. Replies:
    9
    Views:
    927
  5. Eric D.
    Replies:
    3
    Views:
    175
    Jeremy Henty
    Feb 1, 2006
Loading...

Share This Page