1

Today i was asked one question in interview that "If we define instance variable outside the class will it show any error".

class temp():
    a=0
    b=0
    def __init__(self,*args):
        temp.a = args[0]
        temp.b = args[1]
        if len(args)>2 and args[2]:
            print 'extra',args[2]

    def display(self):
        print self.a,self.b,self.c

a = temp(4,9)
b = temp(5,3)
a.c = 20
a.display()

If i run above code i get value of c= 20. I came from c++ background and thought this would be error but not...why it is like that...why python allow to create variable outside class.

3
  • Because you haven't taken any measures to prevent doing so. Commented Aug 29, 2015 at 8:55
  • @IgnacioVazquez-Abrams can u explain?? Commented Aug 29, 2015 at 8:59
  • 1
    FWIW, there's a simple example of adding attributes to an existing class instance in the official Python classes tutorial Odds and Ends Commented Aug 29, 2015 at 10:38

2 Answers 2

3

I recommend reading in the Python docs on Classes and Namespaces. In Python, instances are just another type of namespace, and defining an instance variable outside the class definition involves nothing more than adding an entry in the dictionary of names and values that defines the instance. Contrast this with C, where an instance is an actual block of memory structured according to the pattern laid out in the class definition. Once the class is defined, you can't insert attributes after the fact.

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

Comments

1

In your case, a is an instance of class temp. You can add any attributes to it. In the source code, which you can check it by yourself, it will add this attribute to this instance through simple pointer operation. I think this is the key point of dynamic language which is really different from C++.

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.