1

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 ?

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

2 Comments

@JuanPablo But only until self.s gets set to something else.
@JuanPablo No, it's not. Originally s and self.s are two names for the same object. But then you change the object that self.s is the name for without changing the object that s is the name for.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.