1

I'm having problem creating objects of classes. An object of class has the attributes(i.e fields, methods) of it's class. Can we also define attributes for an object outside the class???

class myclass:
    pass

object1 = myclass()
object2 = myclass()

object1.list = [10]
object1.list.append(4)

object2.fruit = 'apple'

print object2.fruit
print object1.list

OUTPUT:

apple
[10, 4]

Please explain how it is working.

3
  • Did not even know you could do that. I guess I learn something new everyday Commented Apr 4, 2015 at 0:59
  • as you can see in the OUTPUT it's working, so what is your question exactly? Commented Apr 4, 2015 at 1:08
  • list[10] is not defined inside the class, then how can i use it before defining it??? Commented Apr 4, 2015 at 4:08

2 Answers 2

1

(From article mentioned later)

From a little searching a found an article that I believe addresses what your talking about here. After reading it quickly it sounds like that is in fact legal in python. You are creating class attributes. They are only accessible from the class you assign them too. For example print object2.list is invalid. It is basically an instance variable that is exclusive not only to the object type but the object itself.

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

Comments

1

I will try to give this a shot. Sorry in advance if its not clear. What I have read so far this has helped me understand the class objects: https://docs.python.org/2/reference/datamodel.html

A class object is nothing but a namespace with a dict assigned to it. When you add attributes they get added as keys to the dict. You can check this by doing


dir(object1)
dir(object2)

But adding attribute in like the example above cause memory increase, you can stop this behaviour by declaring __slots__

class A(object):
    __slots__ = []

This will stop attribute creation for any instance of A. For more on Usage of __slots__?

Hope this helps

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.