syam syam - 5 months ago 9
Python Question

Can I access a class variable using object of that class

I have two very basic object oriented question

1) Can we modify a class variable with member function?

For example

class test:
'''test class'''

idd=0
def __init__(self,mark,subject):

self.markk=mark
self.subjectt=subject

def display(self):
print "the display is",self.markk,self.subjectt;
stud1=test(30,'maths')
stud2=test(40,'english')


when i tried to modify class variable idd using the object stud1.idd=9;, the variable didnt modified. test.idd=9 modified the variable.

Can someone explain me why it is not possible to modify a class vars from a object?

2) Also in the above snippet, when I added a keyword global with the class var idd like

class test:
'''test class'''
global idd;
idd=0;
print test.idd


it threw error like name class test don't have attribute idd.

But when I commented out the global idd, it displayed value.

So is global keyword not supported in class?

can someone help me to get some idea on these two question as this is my basic step to object oriented concept..

Answer

I think that you're not understanding that python looks up values by looking at a "chain" of objects1. When you do value = self.foo, python will first look for foo on the instance. Then it will look on the class. Then it will look on the super-classes (in their "Method Resolution Order").

When you write:

self.foo = 'bar'

Python simply puts a foo on the instance. So now subsequent lookups on that instance will give you 'bar' even if foo is also defined on the class. Also note that since foo gets put on the instance, no changes are visible on the class.

If you want to update the class in a particular method, you might be able to use a classmethod:

class Foo(object):
    idd = 0
    @classmethod
    def increment_idd(cls):
        cls.idd += 1

f = Foo()
f.increment_idd()
print(Foo.idd)
print(f.idd)

This doesn't work if you need access to self however. In that case, you'll need to get a reference to the class from the instance:

class Foo(object):
    idd = 0
    def increment_idd(self):
        cls = type(self)
        cls.idd += 1

f = Foo()
f.increment_idd()
print(Foo.idd)
print(f.idd)

1If you know javascript, it's actually not too much different than javascript's prototypical inheritance

Comments