1

Please have a look at this:

class Car:
    def __init__(self, bid_code):
        self.__bid = bid_code

    def doit(self, cry):
        self.bid_it = cry

    def show_bid(self):
        print self.__bid

    def show_it(self):
        print self.bid_it

a = Car("ok")
a.show_bid()
a.doit("good")
a.show_it()

What is the scope of bid_it here? I thought it was a local variable, because it is inside a def block. How is it possible that I can call it outside the function? I haven't declared that bid_it is global.

Thanks

1
  • The only time the variable bid_code is used is in the constructor, where it is the parameter. In all other case the property is accessed. Properties are not "scoped" as variables, although they run through a resolution chain. Neither properties nor variables are objects -- they can only contain/refer to objects. Commented May 2, 2011 at 20:02

2 Answers 2

5

By using self, you've bound it to the instance. It's now an instance variable. Instance variables are local to their instances. If the variable were unbound (no self prefix), it'd have function scope and go out of scope once the method call is over, but you've bound it to something else (the instance).

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

1 Comment

@steve If his answer really answered your question, you should accept it as the answer by clicking the check mark. It really helps out the community.
0
def doit(self, cry):
    self.bid_it = cry

'self' acts like a this pointer in c++, in this case a reference to a Car object. If bid_it is not defined in self, it's created on the fly and assigned a value. This means that you can create it anywhere, just as long as you have a reference to your object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.