Search code examples
python-3.xnew-operator

Python use __new__ with no default init


I have some code below to create a Fruit object when no parameter is passed and when a parameter is passed.

For what I am trying to achieve, I get the error message 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()

Solution

  • 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.