[Tutor] Object takes no parameters

Alan Gauld alan.gauld at yahoo.co.uk
Wed Aug 16 21:11:43 EDT 2017


On 17/08/17 01:08, Howard Lawrence wrote:
> class Human:
>      def _init_(self, n, o)
>           self.name = n
>           self.occupation = o
> 

> 
> tom = Human('tom cruise', 'actor')
> 
> Traceback most recent call last
> File "c:\users\shaun\python\python35\human_class.py"line 16 in module
> tom =Human('tom cruise', 'actor')
> TypeError: object() takes no parameters
> 
> how to fix this?why it happens?

If you look closely at your tutorial you will find that init()
has two underscores before and after the name:

def __init__()

rather than

def _init_()

The reason for your error is that all classes inherit from object.
So when you call Human() the interpreter looks for an __init__()
method and, not finding one(because yours only has one undercore),
it looks at the one defined in object. But the object init()
takes no parameters and so there is a mismatch between your
call to Human() and the object.__init__() definition.
Hence the error message.

To fix it use two underscores.

All of the "magic" methods used by Python have these double
underscores and  hence are often referred to as "dunder" methods.
You should avoid defining any new methods (ie new names) with
double underscores yourself, in case Python introduces  a
similar method in a future version.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list