gpt4 book ai didi

python - 为什么它显示 __init__ 函数应该始终不返回任何内容?

转载 作者:行者123 更新时间:2023-12-01 02:31:37 26 4
gpt4 key购买 nike

class Employee:
def __init__(self, first, last, pay):
self.k=first
self.p=last
self.l=pay
self.email=first+'.'+last+'@gmail.com'
h= self.email
return (h)

def fullname(self):
return ('{} {}'.format(self.k,self.p))

emp_1=Employee('Aditya','Shrivastava', 500000)
print(emp_1.fullname())`

异常(exception):

Traceback (most recent call last):
File "A:/Python/Programs/main.py", line 54, in <module>
emp_1=Employee('corey','schafer',50000)
TypeError: __init__() should return None, not 'str'

最佳答案

调用

__init__ 来设置创建的新的空白实例。它始终必须返回None。来自 object.__init__() documentation :

Because __new__() and __init__() work together in constructing objects (__new__() to create it, and __init__() to customize it), no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.

对于没有 return 语句的函数,默认返回 None;从 __init__ 中删除 return (h):

class Employee:
def __init__(self, first, last, pay):
self.k=first
self.p=last
self.l=pay
self.email=first+'.'+last+'@gmail.com'

创建实例后即可访问email属性,无需返回。

关于python - 为什么它显示 __init__ 函数应该始终不返回任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46764983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com