Hello all.
First I have to let you know that Im a total newbie trying to understand Python using the book 'A byte of Python'.
I'm following everything on that book and is been kind of fun until OOP (object orient programing).
Im getting an error in most of the exercises from that book when trying to figure out how the class, object works. Probably is because the Python version? .. Python 3.1.2 this is the one Im using.

I have been trying to solve this my self but I don't have the level of python's understanding to find out what is going on, so , that is why I come to you guys for help.

I received the error: TypeError: object.__new__() takes no parameters
This error is pointing out one line of the scrip: droid1 = Robot('R2-D2')

Here is the code:

#!usr/bin/python
# Filename: objvar.py

class Robot:
    '''Represents a robot with a name.'''

    # A class variable, counting the number of robots
    population = 0

    def _init_(self, name):
        '''Initializes the data.'''
        self.name = name
        print('(Initialzing {0})'. format(self.name))

        # When this person is created, the robot
        # adds to the population
        Robot.population += 1
    def _del_(self):
        '''I am dying.'''
        print('{0} is being destroy!'. format(self.name))

        Robot.population -= 1

        if Robot.population == 0:
            print('{0} was the last one.'. format(self.name))
        else:
            print('There are still {0:d} robots working. '. format(Robot.population))

    def sayHi(self):
        '''Greeting by the robot.


        Yeah, they can do that.'''
        print('Greetings, my master call me {0}'. format(self.name))

    def howMany():
        '''Prints the current population.'''
        print('We have {0:d} robots.'. format(Robot.population))
    howMany = staticmethod(howMany)

droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()

droid2 = Robot('C-3PO')
dorid2.sayHi()
Robot.howMany()


print('\nRobots can do some work here.\n')

print('Robots have finished their work. So lets destroy them.')
del droid1
del droid2

Robot.howMany()

Well, I will thank anyone for expending their time trying to explain me what it is that Im doing wrong or how to fix this problem. I need to know what is going on.
Here is another example that point out a similar line with the same error, also from the same book.

#!usr/bin/python
#Filename: class_init.py

class Person:
    def _init_(self, name):
      self.name = name
    def sayHi(self):
        print('Hello, my name is', self.name)

p = Person('Swaroop')
p.sayHi()

# This short example cam also be written as Person('Swaroop').sayHi()

On this code the error is the same that before:
TypeError: object.__new__() takes no parameters and pointing out the
p = Person('Swaroop') part of the code.

Well, thanks in front and I hope you guys can give me a tip to solve this problem.

Dani AI

Generated

is spot on: the error comes from misspelling the special methods. In Python, these always start and end with double underscores, for example __init__ and __del__. When __init__ is missing, Python falls back to the base object construction path; your argument ('R2-D2') then gets pushed into the default constructor, which does not accept extra arguments, leading to the TypeError you saw. See the language reference on special methods and the object.__new__ / object.__init__ lifecycle. (docs.python.org)

A couple of small improvements to make this example more Pythonic and robust:

  • Use a classmethod for the population counter so you can access class state directly via cls. The built-in docs show how @classmethod works. (docs.python.org)
  • Avoid relying on __del__ for bookkeeping. Finalizers are not guaranteed to run at a predictable time (or at interpreter shutdown), so counts can drift. If you need to track live instances, prefer a weakref container or weakref.finalize. (docs.python.org)

Here is a minimal pattern you can drop in that fixes the dunder names, replaces the staticmethod with a classmethod, and avoids __del__:

#!/usr/bin/env python3
from weakref import WeakSet

class Bot:
    population = WeakSet()

    def __init__(self, name):
        self.name = name
        Bot.population.add(self)

    def say_hi(self):
        print(f'Greetings, my master calls me {self.name}')

    @classmethod
    def how_many(cls):
        print(f'We have {len(cls.population)} robots.')

b1 = Bot('R2-D2')
b2 = Bot('C-3PO')  # note: fixed droid2 typo in the thread
Bot.how_many()
del b1
Bot.how_many()

One last nit: your shebang should be a valid path. For portability, prefer #!/usr/bin/env python3 instead of #!usr/bin/python (missing slash) per PEP 394 guidance. (peps.python.org)

Recommended Answers

All 2 Replies

You have typing error.
Special methods name always have to underscore __init__
special-method-names
Now it should work.

#!usr/bin/python
# Filename: objvar.py

class Robot:
    '''Represents a robot with a name.'''

    # A class variable, counting the number of robots
    population = 0

    def __init__(self, name):   #_init_ wrong __init__ correct
        '''Initializes the data.'''
        self.name = name
        print('(Initialzing {0})'. format(self.name))

        # When this person is created, the robot
        # adds to the population
        Robot.population += 1
    def __del__(self):  #_del_
        '''I am dying.'''
        print('{0} is being destroy!'. format(self.name))

        Robot.population -= 1

        if Robot.population == 0:
            print('{0} was the last one.'. format(self.name))
        else:
            print('There are still {0:d} robots working. '. format(Robot.population))

    def sayHi(self):
        '''Greeting by the robot.


        Yeah, they can do that.'''
        print('Greetings, my master call me {0}'. format(self.name))

    def howMany():
        '''Prints the current population.'''
        print('We have {0:d} robots.'. format(Robot.population))
    howMany = staticmethod(howMany)

droid1 = Robot('R2-D2')
droid1.sayHi()
Robot.howMany()

droid2 = Robot('C-3PO')
droid2.sayHi()  #Typing error
Robot.howMany()


print('\nRobots can do some work here.\n')

print('Robots have finished their work. So lets destroy them.')
del droid1
del droid2

Robot.howMany()

Yes, the error was there because I was using a single '_' and not the '__'(double one). The typing error on droid was also a problem, thanks, it works fine now. :)

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.