如何获取__init__以返回字符串?

时间:2018-12-22 10:25:15

标签: python python-3.x

在这里,我尝试返回一个字符串,但构造函数只能返回一个None值。有什么办法解决吗?

class company:
    def __init__(self):
        self.first_name = str(input("Enter your first name: "))
        self.last_name = str(input("Enter your last name: "))
        self.fullname = self.first_name + " " +self.last_name
        return self.fullname

class salary:
    pay = int(input("Please enter the pay: "))
    def incre(self):
        self.increment = self.pay + 1000
        return self.increment

class Multiderived(company, salary): # here I am using multiple inheritance
    def output(self):
        company.__init__(self)
        salary.incre(self)
        print ("Your full name is: ", self.fullname)
        print ("Your salary is: ", self.increment)

u = Multiderived()
u.output()

在此代码中,我必须使用多重继承来将两个超类的值访问到一个派生类中,但是第一个超类的构造函数无法返回字符串。有什么办法解决吗?

2 个答案:

答案 0 :(得分:3)

不能。您尝试通过以下方法来破坏python规则:请参阅object.__init__()的文档:

  

由于__new__()__init__()在构造对象时共同工作(__new__()用于创建对象,而__init__()用于自定义对象),任何非零值都不能由__init__() 返回;这样做会导致在运行时引发TypeError

(强调我的

答案 1 :(得分:0)

我想这就是您所期望的,我正在使用__str()__

的特殊方法
class Company():
    def __init__(self):
        self.first_name = input("Enter your first name: ")
        self.last_name = input("Enter your last name: ")
        self.fullname = self.first_name + " " +self.last_name
        return self.fullname
class Salary():
    pay = int(input("Please enter the pay: "))
    def incre(self):
        self.increment = self.pay + 1000
        return self.increment
class Multiderived(Company, Salary):
    def __init__(self):
        Company.__init__(self)
        Salary.incre(self)
    def __str__(self):
        return ("Your full name is:"+self.fullname+"\n"+"Your salary is : "+ str(self.increment))
u = Multiderived()
print(u)