Search code examples
pythonclass-variables

Why cant I access class variable from one of it's method as below in Python?


I made a class named 'employee' as below. I can access the class variable 'company' directly through class itself but cant access it using 'getCompany()' method. What is wrong with my code? Since I am newbie to OOP concepts, please grant me detailed but step-wise elaboration of the concepts.

<!-- language: lang-python -->

>>> class employee:
    company = 'ABC Corporation'
    def getCompany():
        return company

>>> employee.company       #####this does as expected
'ABC Corporation'
>>> employee.getCompany()  #####what is wrong with this thing???
Traceback (most recent call last):
   File "<pyshell#15>", line 1, in <module>
     employee.getCompany()
   File "<pyshell#13>", line 4, in getCompany
     return company
NameError: name 'company' is not defined   #####says it is not defined

I am newbie to OOP concepts.


Solution

  • The interpreter is looking for a local variable of that name, which doesn't exist. You should also add self to the parameters, so that you have a proper instance method. If you want a static method instead of an instance method, you'll need to add the @staticmethod decorator. Finally, use the class name to refer to the class variable.

    >>> class employee:
    ...     company = 'ABC Corporation'
    ...     def getCompany(self=None):
    ...             return employee.company
    ...
    >>> employee.company
    'ABC Corporation'
    >>> employee.getCompany()
    'ABC Corporation'
    >>> e = employee()
    >>> e.getCompany()
    'ABC Corporation'
    >>> e.company
    'ABC Corporation'