为什么我不能从Python中的一个方法访问类变量?

时间:2016-10-22 03:58:27

标签: python class-variables

我创建了一个名为' employee'如下。我可以访问类变量' company'直接通过类本身,但不能使用' getCompany()'方法。我的代码出了什么问题?由于我是OOP概念的新手,请授予我详细但逐步的阐述概念。

<!-- 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

我是OOP概念的新手。

2 个答案:

答案 0 :(得分:2)

解释器正在查找该名称的局部变量,该变量不存在。您还应该在参数中添加self,以便拥有正确的实例方法。如果您想要静态方法而不是实例方法,则需要添加@staticmethod装饰器。最后,使用类名来引用类变量。

>>> 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'

答案 1 :(得分: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'

问题Static class variables in Python有更多详情