4 ms·
I personally really like the self keyword after spending some time reading code in Java where `this` is optional. Having to reference self makes it more clear w
by enragedcacti 7y ago
I personally really like the self keyword after spending some time reading code in Java where `this` is optional. Having to reference self makes it more clear where data is coming from and makes navigating an unfamiliar code base much easier. I'm a fan of forcing devs to acknowledge when they are accessing or manipulating mutable object state.
Separate from that, I think that would be a much bigger breaking change than you think. __setattr__ and __setattribute__ means that self.y doesn't necessarily refer to a traditional attribute so without self you could end up with either:
1. `x = y` where the expression `y` executes code
or
2. `x = y` where `x = ???` and `x = self.y` where `x = self.__setattr__('y')`.
That said, I do think the language could use something to reduce the size of __init__() since
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
...
can get pretty verbose
- dfinninger 7y agoTo your last point, check out Dataclasses[1]. @dataclass class Foo: arg1: str arg2: int arg3: int = 5 # default value I use them a lot in my 3.7+ projects. It helps reduce the boilerplate for typical classes. (Where for me, typical classes are a 1:1 mapping of inputs to attributes) And if you need to compute some values at object initialization, then they have a __post_init__() hook you can use [2]. [1] https://docs.python.org/3/library/dataclasses.html https://docs.python.org/3/library/dataclasses.html [2] https://docs.python.org/3/library/dataclasses.html#post-init-processing https://docs.python.org/3/library/dataclasses.html#post-init...
- coldtea 7y ago>Having to reference self makes it more clear where data is coming from and makes navigating an unfamiliar code base much easier. I don't understand this. Aside from people seeing an OOP for the first time in their life, are they getting confused about where "this" comes from? How would an implicit "self" a la "this" make it any less understandable where the data come from? How is passing self making "navigating an unfamiliar code base much easier"? Aside from total newbs who see an OO codebase with an implicit instance variable for the first time?
- fireflash38 7y agoI believe the original commenter was more referring to the lack of 'this' usage in Java. So instead of having: this.x = y People tend to do: x = y Which isn't always the most clear that it's referencing an instance variable rather than a scoped variable, especially if you see it midway through a method.
- coldtea 7y agoA, alright then. I'd go with making this mandatory in that case.
- gowld 7y agoJava fields are declared in the same lexical scope as their use sites (except for inherited fields, but Python has the same magic in that case.)