JuanPablo
JuanPablo

Reputation: 24804

attributes in python class

I have problem updating attributes in a python class, I give a small example.

#!/usr/bin/python
# -*- coding: utf-8 -*-
class myClass():
    def __init__(self):
        self.s=0
        self.procedure()
    def procedure(self):#{{{
        s=self.s
        print s
        self.operation()
        print s
    def operation(self):#{{{                                                                                            
        s=self.s
        s+=1
        self.s=s
        print "o:",self.s
c=myClass()

then output

0
o: 1
0

why the last number is 0 and not 1 ?

Upvotes: 1

Views: 291

Answers (4)

Karl Knechtel
Karl Knechtel

Reputation: 61643

Because s = self.s doesn't make s another name for "whatever you get by checking self.s, always and forever"; it makes s another name for "whatever self.s currently refers to".

The integer 0 is an object. In the first function, you cause self.s and s to both refer to that object, and then cause self.s to refer to something else (the result of the addition) via another s that's local to the other function. The s local to the first function is unchanged.

Upvotes: 1

user
user

Reputation: 7333

Your procedure code should read:

def procedure(self):#{{{
        s=self.s
        print s
        self.operation()
        # the following line is edited
        print self.s

Otherwise, the variable you change (self.s) doesn't print.

Upvotes: 1

Michael Hoffman
Michael Hoffman

Reputation: 34364

in myClass.procedure(), you create the local name s with a value copied from self.s, which is 0. In myClass.operation(), you set self.s to 1. But you haven't overwritten your previous copy to s in myClass.procedure(), so it is still 0.

Upvotes: 2

Chris Lacasse
Chris Lacasse

Reputation: 1562

You are printing s instead of self.s in the last print.

Upvotes: 1

Related Questions