[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/psvm-enter/LearnPython/master/python_magic_methods.py [Back]  [Original]

# _*_ coding: utf-8 _*_

"""
python_magic_methods.py by xianhu
"""


# People
class People(object):

    def __init__(self, name, age):
        self.name = name
        self.age = age
        return

    def __str__(self):
        return self.name + ":" + str(self.age)

    def __lt__(self, other):
        return self.name < other.name if self.name != other.name else self.age < other.age

print("\t".join([str(item) for item in sorted([People("abc", 18), People("abe", 19), People("abe", 12), People("abc", 17)])]))


# Python a[0] = 'value1'; a[1][2] = 'value2'; a[3][4][5] = 'value3'
class MyDict(dict):

    def __setitem__(self, key, value):          #  
        print("setitem:", key, value, self)
        super().__setitem__(key, value)
        return

    def __getitem__(self, item):                # 
        print("getitem:", item, self)
        # : a[1][2] a[1] a[1][2]
        if item not in self:                    # a[1]
            temp = MyDict()                     # dict
            super().__setitem__(item, temp)     # a[1] = dict
            return temp                         # a[1] a[1][2] = value
        return super().__getitem__(item)        # a[1] a[1]

# :
test = MyDict()
test[0] = 'test'
test[1][2] = 'test1'
test[3][4][5] = 'test2'
print("==========================")

Web Proxy Viewer  |  New URL  |  Original Page