Naresh
Naresh

Reputation: 1972

Define Instance variable outside the class

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.

Upvotes: 1

Views: 1758

Answers (2)

morrna
morrna

Reputation: 106

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.

Upvotes: 3

Stephen Lin
Stephen Lin

Reputation: 4912

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++.

Upvotes: 1

Related Questions