0

I have this code in my python script

class Class(object):
    client_id = ''

    @classmethod
    def get_client_id(cls):
        return cls.client_id


class Service(object):

    @staticmethod
    def get_class():
        cls_obj = Class()
        cls_obj.client_id = 'this is client id'
        return cls_obj

print(Service.get_class().get_client_id())

but when i run the python script, it displays empty string and not the 'this is client id'. please help

inferno
  • 45
  • 6

2 Answers2

1

You're setting the property on an instance of the class, not the class itself -- that doesn't percolate up to the class or anything. The class method getter however looks on the class, so it doesn't find it. Remove @classmethod and it will work.

jwilner
  • 6,348
  • 6
  • 35
  • 47
1

Because you are literally changing the cls_obj.client_id, not cls.client_id.

Note that you could access the class variable client_id with cls_obj.client_id, but if you assign to it, you just add an instance variable to cls_obj. Now you have both cls.client_id and cls_obj.client_id, next time you try cls_obj.client_id you'll get the instance variable.

satoru
  • 31,822
  • 31
  • 91
  • 141