martinho
martinho

Reputation: 3379

Python class and object creation

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.

Upvotes: 1

Views: 92

Answers (2)

skar
skar

Reputation: 401

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

Upvotes: 1

JGerulskis
JGerulskis

Reputation: 808

(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.

Upvotes: 1

Related Questions