使用备用构造函数执行代码时出错 [英] Error in executing code using alternate constructor

查看:84
本文介绍了使用备用构造函数执行代码时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用此备用构造函数调用方法,但无法调用pay和email,它表示employee object没有属性pay。知道为什么会这样吗



我尝试过:



班级员工:
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( - )
返回cls(first,last,pay)

emp1 = employee(ali,20,20000)

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

解决方案

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)


这篇关于使用备用构造函数执行代码时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆