[我正在尝试编写一个具有Emp类并使所有Emp类成员可用于另一个类的程序

问题描述 投票:0回答:1

[我正在尝试编写一个具有Emp类的程序,并将Emp类的所有成员提供给另一个类。

但是我收到属性错误。

代码:

#create class and make all member of call available for another class

class Employee():
    #this is method

    def Display(self,a,id,sal):
        print("Name of the Employee",a)
        print("Id of the employee",id)
        print("salary of the employee",sal)


class Myclass():

    def MyMethod(emp_object):
        emp_object.sal=emp_object.sal+1000
        emp_object.Display("abc",121,5000)


emp_object= Employee()
emp_object.Display("abc",121,5000)
Myclass.MyMethod(emp_object)

错误

[AttributeError:'Employee'对象没有属性'sal']

python
1个回答
2
投票

我认为最好阅读https://docs.python.org/3/tutorial/classes.html,以进一步了解类。关于您的问题,修改Display方法将解决此问题。

class Employee():
    #this is method
    def __init__(self):
        self.a = ''
        self.id = 0
        self.sal = 0

    def Display(self,a,id,sal):
        #If you want to override the values, just reassign them
        self.a = a 
        self.id = id
        self.sal = sal
        print("Name of the Employee",a)
        print("Id of the employee",id)
        print("salary of the employee",sal)
© www.soinside.com 2019 - 2024. All rights reserved.