【问题标题】:Not able to access object member variables无法访问对象成员变量
【发布时间】:2018-06-04 06:04:00
【问题描述】:

我是 python 新手,遇到一个奇怪的错误。
我的演示的基本思想是在 python 中执行“构造函数重载”,类似于其他编程语言。 我有两个文件,一个文件只保存类,另一个文件用于创建类的对象。

employee.py

class Employee:
  def displayEmployee(self):
    print("Name : ", self.emp_name,  ", Salary: ", self.salary)

  def __init__(self,id=None,salary=None,emp_name=None):
      print("Constructing MyClass")
      if(id is None):
        self.id=101
      else:
        self.id = id
      if(salary is None):
        self.salary=20000
      else:
        self.salary = salary
      if(emp_name is None):
        self.emp_name="Default"
      else:
        self.emp_name = emp_name

runner.py

from employee import Employee

emp1 = Employee()
emp2 = Employee(1,3000,"Abcd")

emp1.displayEmployee();
emp2.displayEmployee();

但是,现在我面临一个错误,因为

Traceback (most recent call last):
File "runner.py", line 7, in <module>
  emp2.displayEmployee();
File "D:\python\Demo\employee.py", line 3, in displayEmployee
  print("Name : ", self.emp_name,  ", Salary: ", self.salary)
AttributeError: 'Employee' object has no attribute 'emp_name'

这意味着我无法在同一类的函数中访问该类的任何成员变量。对于其他编程语言,这让我很困惑。
我做错了什么还是设计使然?

更新:

根据建议,我已将 python 文件更新为以下内容。但是,我仍然面临同样的错误,下面也给出了。

employee.py

class Employee:
  def displayEmployee(self):
    print("Name : ", self.emp_name,  ", Salary: ", self.salary)

def __init__(self, id=101, salary=20000, emp_name="Default"):
    print("Constructing MyClass")
    self.id = id
    self.salary = salary
    self.emp_name = emp_name

runner.py

from employee import Employee

emp1 = Employee()
emp1.displayEmployee();

错误:

Traceback (most recent call last):
  File "runner.py", line 6, in <module>
    emp1.displayEmployee();
  File "D:\python\Demo\employee.py", line 3, in displayEmployee
    print("Name : ", self.emp_name,  ", Salary: ", self.salary)
AttributeError: 'Employee' object has no attribute 'emp_name'

【问题讨论】:

  • 您忘记了 if None 比较中的 else 语句。例如,您如何期望 ID 不是 None 或 101?另外,python不需要分号

标签: python oop constructor


【解决方案1】:

如果您传递的参数不是None,它们永远不会被分配为self 的属性。您可以修改您的 __init__ 以简单地提供默认值,然后将它们作为属性分配给您的类

def __init__(self, id=101, salary=20000, emp_name="Default"):
    print("Constructing MyClass")
    self.id = id
    self.salary = salary
    self.emp_name = emp_name

【讨论】:

  • 我已经听从了你的建议,但我仍然遇到同样的错误。请检查我对问题的更新。
  • @Samwell Tarly 在更新的employee.py 中,修复def __init__ 上的缩进与def displayEmployee 相同,之后,它对我有用。
  • @SangminKi​​m,正确!看来我与习惯 python 的缩进风格有很大关系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多