j: Next unread message
k: Previous unread message
j a: Jump to all threads
j l: Jump to MailingList overview
On Sun, May 14, 2017 at 2:53 PM, Brendan Barnwell email@example.com wrote:
Attributes aren't just for passing things to other methods. They're
for storing state. In your proposed system, how would an object mutate one of its own attributes? It looks like "x" here is just stored in a function closure, which wouldn't allow easy mutation. Also, how would another object access the attribute from outside (as we currently do with self.x)? You can say we'd only use this new attribute-free approach when we want to pass a constructor argument that's used but never mutated or accessed from outside, but that severely restricts the potential use cases, and all it saves you is typing "self".
My expectation is that you'd be using "nonlocal x" to do that.
Closures can be used to emulate classes (and vice versa). However, in Python, the syntax for reaching outside a method to access the closure is significantly clunkier than the equivalent in C-derived languages:
def outer(): x = 0 def inner(): nonlocal x x += 2
Is it better to say "nonlocal" on everything you use than to say "self.x" on each use? I say no, because it makes copying and pasting code dangerous - reading attributes will work, but mutating them requires the nonlocal tag. With "self.x", it's the same on both, and it's the same in all methods.