-1

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.

Community
  • 1
  • 1

2 Answers2

2

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'
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • Yeah, I got it. The main point was that the 'company' variable was not defined within the method. And we cant simply access the class variable only by class variable name. – Prakash Bhattarai Oct 22 '16 at 12:18
0
In [1]: class employee:
   ...:     company = "ABC Corporation"
   ...:     def getCompany(self):
   ...:         return self.company
   ...:

In [2]: employee.company
Out[2]: 'ABC Corporation'

In [3]: employee().getCompany()
Out[3]: 'ABC Corporation'

In [4]: class employee:
   ...:     company = "ABC Corporation"
   ...:
   ...:     @classmethod
   ...:     def getCompany(self):
   ...:         return self.company
   ...:

In [5]: employee.company
Out[5]: 'ABC Corporation'

In [6]: employee.getCompany()
Out[6]: 'ABC Corporation'

Question Static class variables in Python has more details

Community
  • 1
  • 1
Garland
  • 1
  • 1