1

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?

2 Answers 2

1

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.

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

3 Comments

But why cp1 is still an instance of cartesianPoint even after addind two data memebers specific to cp1???
check that link: rosettacode.org/wiki/…
You can think of that simply as: Python is a dynamic scripting language, so It allows the users to define object data members and methods dynamically but Python will not bind it back to the class of that object. Hope that helps
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.