BiBi
BiBi

Reputation: 7908

Using a class instance inside itself

Is it considered bad practice to use a class inside itself? For instance:

class Foo:
    def __init__(self, b=None):
        """
        b  (Foo|None): instance of Foo.
        """
        self.a = 'hello'
        if isinstance(b, Foo):
            print(b.a)

Upvotes: 1

Views: 213

Answers (2)

Primusa
Primusa

Reputation: 13498

No. There's no point in going out of your way to use a class inside itself but if it solves your problem then go for it. For example python's standard library OrderedDict has an instance where it uses itself inside it's own definition:

def __eq__(self, other):
    '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
    while comparison to a regular mapping is order-insensitive.

    '''
    if isinstance(other, OrderedDict):
        return len(self)==len(other) and \
               all(_imap(_eq, self.iteritems(), other.iteritems()))
    return dict.__eq__(self, other)

Upvotes: 4

Daniel Pryden
Daniel Pryden

Reputation: 60957

No, it's fine. This is actually a pretty common pattern for implementing something like a tree or linked list node.

Upvotes: 2

Related Questions