0

I just observed how the classes are different in python when compared with C++. Like, In C++

Class test

{


    int  a,b;

    Void  func()

    {

    }  

}

In the above class template, a and b are only Object variables which are defined in the template.

Whereas, in python, you can’t specify what and all the object variables the class can have in class definition.

Like,

Class student(self):

    def func(self,x)
        pass

In the above class template, we can’t define any Object variables . dir (student) will give a list of functions and class variables only.

suppose if am instantiating an object of this class, Say, S. If I want to give a name to that student then, S.name = “ “ will do

Now dir(S) will show the name attribute whereas dir(student) won’t have a name field For me it sounded a little weird .

The interpreting feature of python allows to add as many fields as we want to the object that's fine.

questions that came to me was

  1. why they didn’t provided the feature of defining variables in class definition? , And

  2. how the memories are reserved during instantiation and modified when new variables are added to the objects?

Thanks,

-kallis

Danica
  • 28,423
  • 6
  • 90
  • 122
Kallis Kalyan
  • 17
  • 1
  • 2

1 Answers1

2
  1. Python emphasizes dynamic typing, so you can add variables whenever you want. You can add any variables you want to be there in the __init__ constructor. You also might want class variables. If you really want, you can override the __setattr__ method to stop people from adding new attributes. You could also use __slots__, but you shouldn't.

  2. If you don't use __slots__, attributes are stored in the __dict__ dictionary. So a class instance itself takes only the space of a dictionary pointer (plus a few other small things).

Community
  • 1
  • 1
Danica
  • 28,423
  • 6
  • 90
  • 122