Timeline for How do I avoid the "self.x = x; self.y = y; self.z = z" pattern in __init__?
Current License: CC BY-SA 3.0
11 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Feb 26, 2016 at 9:47 | audit | First posts | |||
Feb 26, 2016 at 9:47 | |||||
Feb 16, 2016 at 1:40 | audit | First posts | |||
Feb 16, 2016 at 1:53 | |||||
Feb 12, 2016 at 21:45 | audit | First posts | |||
Feb 12, 2016 at 22:21 | |||||
Feb 4, 2016 at 12:31 | comment | added | mike3996 |
@hamstergene: it's solely a good thing. ;) The only downside is that you have to write your own update methods (that return a fresh copy with a particular field updated)
|
|
Feb 4, 2016 at 11:26 | comment | added | hamstergene |
The problem with namedtuple is that they are read-only. You can not do abc.x += 1 or anything like that.
|
|
Feb 4, 2016 at 5:03 | comment | added | detly |
I often use namedtuple s for this exact purpose, especially in mathematical code where a function might be highly parametrised and have a bunch of coefficients that only make sense together.
|
|
Feb 4, 2016 at 3:56 | comment | added | A Small Shell Script | Thanks @PaulMcGuire. I was trying to think of a really simple add-on to show the inheritance and kind of spaced on that. You're 100% right and it's a great shorthand with other inherited objects, too! I do mention the field names can be comma or space separated -- I prefer CSV from habit | |
Feb 4, 2016 at 3:55 | comment | added | PaulMcG |
Also, your namedtuple declaration string does not require commas between the fieldnames, XYZ = namedtuple("XYZ", "x y z") works just as well.
|
|
Feb 4, 2016 at 3:52 | comment | added | PaulMcG |
These are tuples, so your properties method can be written as just return tuple(self) , which is more maintainable if in future more fields are added to the namedtuple definition.
|
|
Feb 4, 2016 at 2:53 | history | edited | A Small Shell Script | CC BY-SA 3.0 |
added 50 characters in body
|
Feb 4, 2016 at 2:48 | history | answered | A Small Shell Script | CC BY-SA 3.0 |