I am a bit new to Oops and I am getting confused with Python classes.Though I studied C++ in high school, but I know what I studied back then wasn’t C++ at all(It was kind of C with classes, no templates, STL, or namespace)
Correct me if I am wrong, but for me classes are just blueprints for objects, right?
Now if I wanted to create an instance of a class in C++(For eg, my class name is “animal”)
I would do this:
animal lion;
or if I had a constructor(with arguments) then only I would do thisanimal tiger(4,5);
The problem I am facing is:
class animal:
val = 5
Its just a basic class, without any constuctor or methods:
Now with python I am able to reference animal as it is without creating any instances of it(I coudn’t do that in C++, right?)
animal.val = 7
Another problem I am facing is,I need to use parenthesis always while creating instances, or it will refer to the class itself.
For eg;
lion = animal
lion.val = 6
tiger = animal
print tiger.val
and it prints 6,when I want to create an instance I’ve to use paranthesis, even though I haven’t specified any constructor(Which wasn’t necessary in C++), any special reason or just a matter of language syntax?
Everything in Python is an object. Classes are objects that create other objects.
Thus, when you reference
animal.val, you’re referencing the class propertyvalon the classanimal.If you want to actually create an object of type
animal, you’d call the class and get an instance back:Anything you set on that instance is then set for only that instance (whereas changes to the class are shared among all objects created via the class).
See here for more details about classes in Python.