1

I have a class that has a classmethod and a instance method..The classmethod creates a class variable cls.name.

I would like to know how to access the class variable cls.name in my instance method - parent_method.

class Parent():
        def __init__(self):
            print "Parent initialized"

        @classmethod    
        def resource_setup(cls):
            cls.name = "P"
            print "parent method"

        def parent_method(self):
            print self.name
user1050619
  • 19,822
  • 85
  • 237
  • 413

2 Answers2

0

You need to call that class method in order for the name to come into existence.

BTW, since you're using Python 2 you should explicitly derive your classes from object, otherwise you get old-style classes.

Here's a quick demo (running on Python 2.6.6)

class Parent(object):
    def __init__(self):
        print "Parent initialized"

    @classmethod
    def resource_setup(cls):
        cls.name = "P"
        print "parent method"

    def parent_method(self):
        print self.name

Parent.resource_setup()
a = Parent()
a.parent_method()
print a.name

output

parent method
Parent initialized
P
P

Note that you don't need to call .resource_setup() via Parent, you can also do it using an instance, but I think it's more explicit to call class methods using the class name. The code below uses the same class definition as above, so I won't repeat it.

a = Parent()
a.resource_setup()
a.parent_method()

b = Parent()
b.parent_method()

output

Parent initialized
parent method
P
Parent initialized
P
Community
  • 1
  • 1
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

You can access class variable from instance after you initialized it in class method.

p = Parent()
p.resource_setup()
p.parent_method()

Class and instance variables are in different namespaces. When you call attribute the first lookups are in instance dictionary

p.__dict__

next in class dictionary

p.__class__.__dict__

and so on in dictionaries from instance class being inherited.

maxfrei
  • 456
  • 4
  • 3