1

For example, consider the following class:

class A:
    def __init__(self):
        self.attr1 = value
        self.attr2 = self.foo()
    def foo(self):
        return self.attr1 ** 2

Is this the right way, should I pass attr1 to foo as a parameter or should I define foo outside the class?

Vinayak Mehta
  • 369
  • 4
  • 12
  • Watch out - any method you call this way is completely unsafe to override. For example, if you try to log the `repr` of your objects every time you create one, `__repr__` cannot be safely overridden by subclasses. (There are ways you can try to kludge around this problem, but they're completely unsafe.) – user2357112 Nov 15 '16 at 21:16

1 Answers1

2

This is totally fine, and a common pattern -- you just have to be careful you've already set all the attributes foo() cares about before calling it.

This is often used when defining container classes. For example, a list-like class:

class ListLike:
    def __init__(self, items=[]):
        self.lst = []
        self.thingy = 'foo'
        for item in items:
            self.add(item)

    def add(self, item):
        self.lst.append(item)
Ben Hoyt
  • 10,694
  • 5
  • 60
  • 84
  • Note that a mutable default argument is [not a great idea](http://stackoverflow.com/q/1132941/3001761). – jonrsharpe Nov 15 '16 at 21:34
  • 1
    @jonrsharpe, thanks -- I'm definitely aware of the issues with mutable defaults. But it's only a problem if you're actually mutating it, which I'm not here, so it's simpler and more efficient. Alternatively, you could do `items=None` and then `for item in items or []:`. – Ben Hoyt Nov 16 '16 at 14:19