user2688772
user2688772

Reputation: 347

OOP instance updating

I just started With OOP and i am confused with this code-

class cartesianPoint:

       pass

cp1 = cartesianPoint()

cp1.x = 1.0

cp1.y = 2.0

cp1

>
<__main__.cartesianPoint instance at 0x0000000001E7EB88>

Firstly Why I am able to add new variables to object which do not belong to the Class?If class is a blueprint for objects,shouldnt the objects follow the buleprint ? And even though python allows you to do so, why does the object still belong to the same class?

Upvotes: 1

Views: 66

Answers (2)

falsetru
falsetru

Reputation: 369444

According to Python tutorial - Classes - Instance Objects:

data attributes correspond to “instance variables” in Smalltalk, and to “data members” in C++. Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to.

Using __slots__, you can prevent new instance variable being assigned.

Upvotes: 1

Rami
Rami

Reputation: 7300

Check section 9.4 here: http://docs.python.org/2/tutorial/classes.html

Note that clients may add data attributes of their own to an instance object without affecting the validity of the methods, as long as name conflicts are avoided

cp1 is indeed an instance of the CartesianPoint class but you have added 2 new data members to that specific instance which has no effect on the class itself or any subsequent instances.

Keep in mind that each instance of the CartesianPoint class has its own dict of fields and methods.

Upvotes: 1

Related Questions