【问题标题】:Why cant I access class variable from one of it's method as below in Python?为什么我不能从 Python 中的以下方法之一访问类变量?
【发布时间】:2016-10-22 03:58:27
【问题描述】:

我创建了一个名为“employee”的类,如下所示。我可以直接通过类本身访问类变量“公司”,但不能使用“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 概念的新手。

【问题讨论】:

    标签: python class-variables


    【解决方案1】:

    解释器正在寻找该名称的局部变量,但该变量不存在。您还应该将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'
    

    【讨论】:

    • 是的,我明白了。要点是“公司”变量未在方法中定义。而且我们不能简单地通过类变量名来访问类变量。
    【解决方案2】:
    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有更多详情

    【讨论】:

      猜你喜欢
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 2011-06-10
      • 2014-03-28
      • 2018-07-31
      • 1970-01-01
      相关资源
      最近更新 更多