且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用备用构造函数执行代码时出错

更新时间:2022-10-15 12:56:34

alternatecontructor 方法不是实际的构造函数。它创建的属性不属于你的类。



当你调用该方法时,它会返回一个新的员工使用字符串中的值创建的对象。但是,类的属性是在实际构造函数中指定的属性,即 name age SAL 。因此,更改代码以使用正确的属性名称:

  print (newobj.sal)


I am able to call methods using this alternate constructor but am unable to call pay and email , it says "employee object has no attribute pay". any idea why this is happening

What I have tried:

class employee:
    def __init__(self, name , age ,sal):
        self.name= name
        self.age=age
        self.sal=sal

    def creds(self):
        return(self.name, self.age, self.sal)

    def bio(self):
        print(self.name + str(self.age))


    @classmethod
    def alternatecontructor(cls,str):
        first,last,pay = str.split("-")
        return cls (first,last,pay)

emp1= employee("ali",20,20000)

str1 = "ibbi-26-50000"
newobj= employee.alternatecontructor(str1)
print(newobj.bio())
print(newobj.pay)

The alternatecontructor method is not an actual constructor. And the attributes that it creates are not part of your class.

When you call that method it returns a new employee object created with the values from the string. However the attributes of the class are the ones specified in the actual constructor, i.e name, age and sal. So change your code to use the correct attribute name thus:
print(newobj.sal)