HELP : class and variables

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • vincent delft

    HELP : class and variables

    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[color=blue][color=green]
    >> 3[/color][/color]
    t.var1=6
    print t.res[color=blue][color=green]
    >> 3[/color][/color]

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

    Thanks
  • Bruno Desthuilliers

    #2
    Re: HELP : class and variables

    vincent delft wrote:[color=blue]
    > 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
    >[color=green][color=darkred]
    >>>3[/color][/color][/color]

    Until here, t.var1 means test.var1 (class variable)
    [color=blue]
    > t.var1=6[/color]

    From here, you created a new instance variable for object t, named
    var1. It hides test.var1.
    [color=blue]
    > print t.res
    >[color=green][color=darkred]
    >>>3[/color][/color][/color]

    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 :[color=blue][color=green][color=darkred]
    >>> class test:[/color][/color][/color]
    .... def __init__(self):
    .... # create instance variables
    .... self.var1 = 1
    .... self.var2 = 2
    .... def res(self):
    .... return self.var1 + self.var2
    ....[color=blue][color=green][color=darkred]
    >>> t = test()
    >>> t.res()[/color][/color][/color]
    3[color=blue][color=green][color=darkred]
    >>> t.var1 = 6
    >>> t.res()[/color][/color][/color]
    8

    Bruno

    Comment

    • Bertel Lund Hansen

      #3
      Re: HELP : class and variables

      vincent delft skrev:
      [color=blue]
      >Can you explain the following ?[/color]

      Yes.
      [color=blue]
      >class test:
      > var1=1
      > var2=2
      > res=var1+var2[/color]
      [color=blue]
      >t=test()
      >print t.res[color=green][color=darkred]
      >>> 3[/color][/color][/color]
      [color=blue]
      >t.var1=6
      >print t.res[color=green][color=darkred]
      >>> 3[/color][/color][/color]

      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

      Comment

      Working...