Pythonic style
Ethan Furman
ethan at stoneleaf.us
Wed Apr 27 23:52:24 EDT 2016
On 04/27/2016 08:07 PM, Christopher Reimer wrote:
> On 4/27/2016 7:07 PM, Ben Finney wrote:
>> Ian Kelly wrote:
>>> self.__dict__ = {'key', 'value'}
>>>
>>> is essentially equivalent to:
>>>
>>> self.key = value
>>
>> I would say the latter is more Pythonic, because it:
>>
>> [snip]
>>
>> * Uses the built-in mechanisms of Python (don't invoke magic attributes,
>> instead use the system that makes use of them behind the scenes).
>
> In short, my original code before I turned it into a separate
> dictionary. *sigh*
No.
The point Ben was trying to make is this: you should never* call
__dunder__ methods in normal code; there is no need to do so:
- use len(), not __len__()
- use next(), not __next__()
- use some_instance.an_attribute, not some_instance.__dict__['an_attribute']
--
~Ethan~
* Okay, maybe /almost/ never. About the only time you need to is when
giving your classes special methods, such as __add__ or __repr__.
More information about the Python-list
mailing list