Home > Enterprise >  Python use __new__ with no default init
Python use __new__ with no default init

Time:10-15

I have the below code to create Fruit Object when no parameter is passed and when parameter is passed.

I am trying to achieve, for which I get TypeError: object() takes no parameters

class Fruit:
    
    def __new__(cls, *args, **kwargs):
        return object.__new__(cls,"empty name")
        
    def __init__(self, fruitname):
        self.__fruit_name = fruitname

Expected code to work.

  apple = Fruit("apple")
  empty = Fruit()

CodePudding user response:

The correct way to do this would be to subclass:

class Fruit(object):
    def __new__(cls, *args, **kw):
        return super().__new__(cls)

What you will likely see with your code is:

TypeError: object.__new__() takes exactly one argument (the type to instantiate)

Because you're passing an extra parameter that isn't supported.

But the __new__ is redundant. There is no need for you to use it at all here, and unless you're doing some fancy metaprogramming stuff, it's likely you never need to override __new__ at all.

Just intialise all your variables in __init__, and you should be fine.

CodePudding user response:

I think the following should be sufficient for what you have described:

class Fruit:

  def __init__(self, fruitname = "empty name"):
    self.__fruit_name = fruitname

The reason for the error is an improper use of object.__new__() (This function does not expect any parameters) which is actually not necessary here.

  • Related