some dict's special methods - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: some dict's special methods (/thread-14810.html) |
some dict's special methods - nzcan - Dec-18-2018 hello, i suppose that behind the: >>> ca = {1:'koko', 2:'boko'} >>> 1 in ca True >>> 5 in ca Falsestays the dict's dunder '__contains__' but i am not so sure which duner exactly stays behind: >>> ca = {1:'koko', 2:'boko'} >>> ca [3] = 'loko' >>> ca {1: 'koko', 2: 'boko', 3: 'loko'} >>>i think it could be '__setitem__', but i am not sure. is this '__setitem__' or some other special method? thanks in advance! RE: some dict's special methods - buran - Dec-18-2018 It's easy to check it >>> foo=dict() >>> foo.__setitem__('key', 'value') >>> foo {'key': 'value'} >>> RE: some dict's special methods - nzcan - Dec-18-2018 and what operation executes dict's '__getattribute__' special method? RE: some dict's special methods - buran - Dec-18-2018 I would suggest you read Data Model | Special method names section from the docs __getattribute__() >>> foo = {'foo':1, 'bar':2} >>> foo.__getattribute__('keys') <built-in method keys of dict object at 0x7fe05ce3fb88>As you can see it returns the built-in method dict.keys() Emulating container types Note that opposite to __setitem__() is __getitem__() RE: some dict's special methods - nzcan - Dec-18-2018 Quote:As you can see it returns the built-in method dict.keys()does it means that behind every dict's built-in method stay one dict's special method? RE: some dict's special methods - buran - Dec-18-2018 (Dec-18-2018, 05:02 PM)nzcan Wrote: does it means that behind every dict's built-in method stay one dict's special method?No, I don't know how you come to that conclusion. As it state in the docs Quote:A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators.That's true for every class, builtin or custom. >>> dir(dict) ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']e.g. __str__ is called when you do str(some_dict)special methods are methods/attributes, there is no other front-line methods/attribute |