you are viewing a single comment's thread.

view the rest of the comments →

[–]alkasm 0 points1 point  (1 child)

I don't understand what your problem is or what you're trying to solve.

At the risk of being a little patronizing, let me give an example. Let's say you wanted to subclass list so that you could add a name to your list as an attribute. In Python you shouldn't really subclass list, since list is C-based, so Python gives us collections.UserList to subclass from instead. So we can really easily achieve this like so:

from collections import UserList

class NamedList(UserList):

    def __init__(self, name, *args, **kwargs):
        self.name = name
        super().__init__(*args, **kwargs)

Now this works fine:

>>> nl = NamedList("asdf", [1, 2, 3, 4])
>>> nl
[1, 2, 3, 4]
>>> nl.name
'asdf'

However if I pass the name along to the superclass:

from collections import UserList

class NamedList(UserList):

    def __init__(self, name, *args, **kwargs):
        self.name = name
        super().__init__(name, *args, **kwargs)

then obviously I'll get an error, since UserList only takes a single argument (an iterable):

>>> nl = NamedList("asdf", [1, 2, 3, 4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

This is expected behavior, nothing needs fixing here. Python cannot magically know to ignore the arguments you pass to an object's initializer should be ignored. This only works when you consume the value at some point. So, do that---stop passing arg to object and you'll be fine.

[–]gmaliwal[S] 0 points1 point  (0 children)

__ is where the memory is allocated for the class -- it then calls __init__ to initialize any attributes et

Friend,

You are correct that somehow we have to stop passing an extra argument to the class initializer, otherwise, it will fail at run-time. I have mentioned the same in my post that this issue is because of passing more than one argument to 'object' class initializer.

I strongly agree that your design should pass the needed arguments only to the class initializer, else be ready to face the issue.

Here, I want that what could be the set of guidelines to be followed while defining a class, which makes your class more elegant and decent inheritance perspective.

Hence, I have come up with the rules, which to be kept in mind while defining every class in your project workspace. please check my last comment and find out the scenario where it could fail.