Aditya Shrivastava
Aditya Shrivastava

Reputation: 55

why does it show that __init__ function should always return none?

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())`

Excepton:

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'

Upvotes: 0

Views: 1485

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121186

__init__ is called to set up the new, blank instance created. It always must return None. From the 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.

Returning None is the default for a function without a return statement; remove the return (h) from __init__:

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

You can access the email attribute after creating the instance, there is no need to return it.

Upvotes: 2

Related Questions