I have two very basic object oriented question
1) Can we modify a class variable with member function?
print "the display is",self.markk,self.subjectt;
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
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)