Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python Advanced Objects Subclassing Built-ins

Kento Nambara
Kento Nambara
1,764 Points

What is the point of having *args and **kwargs as arguements when overriding __new__ or __init__?

I just cannot understand this concept. I understand init, but I also do not completely understand the concept of new.

Jamaru Rodgers
Jamaru Rodgers
3,046 Points

I would also like a refresher from a fellow student or from the staff! It always gets me. Sorry for bringing up this old post but I saw it didn't have an answer :)

1 Answer

Well I'll say the key usage of dunder init and dunder new are quite similar and different the first handles how an instance of your objects are created at run time with the later contains logic on how the class should be created. The constructor init for instance handles setting instance values while new will often contain a hook to intercept how the class is created detecting if the class has certain attributes and can even contain logic to override the class properties.

For example

class A(object):
    def __init__(self, count=0):
        self.count = count

class A(object):  # -> don't forget the object specified as base

    def __new__(cls):
        print("A.__new__ called")
        return super(A, cls).__new__(cls)

    def __init__(self):
        print("A.__init__ called")

# A()
# A.__new__ called
# A.__init__ called

Check out https://spyhce.com/blog/understanding-new-and-init and https://howto.lintel.in/python-__new__-magic-method-explained/ for more information.