My Note / Zeliang YAO
  • Zeliang's Note
  • Dremio
    • Custom Class
  • 💕Python
    • Design Pattern
      • Creational
        • Abstract Factory
        • Factory Method
        • Singleton
        • Builder / Director
      • Structural
        • Adapter
    • Boto3
    • Typing
    • String
    • Requests
    • Iterator & Iterable
      • Consuming iterator manually
      • Lazy Iterable
    • Genrators
    • itertools
    • Collections
    • Customization
      • Customize built-in
      • Logging
      • Hdf5
      • Sqlite3 & Df
    • Pandas
      • Basic
      • Data cleaning
      • Merge, Join, Concat
      • Useful tricks
      • Simple model
      • Pandas acceleration
    • Pandas time series
      • Date Range
      • Datetime Index
      • Holidays
      • Function_to_date_time
      • Period
      • Time zone
    • *args and**kwargs
    • Context Manager
    • Lambda
    • SHA
    • Multithreading
      • Threading
      • Speed Up
    • Email
    • Improvement
    • Useful functions
    • Python OOP
      • Basic
      • @static / @class method
      • attrs module
      • Dataclasses
      • Dataclasses example
      • Others
    • Design patterns
      • Creational Patterns
      • Structural Patterns
      • Behavioral Patterns
  • 🐣Git/Github
    • Commands
  • K8s
    • Useful commands
  • Linux
    • Chmod
Powered by GitBook
On this page

Was this helpful?

  1. Python
  2. Customization

Customize built-in

UserDict

from collections import UserDict
class LowerDict(UserDict):
    def __setitem__(self, key, value):
        key = key.lower()
        super().__setitem__(key, value)


ordinals = LowerDict({"FIRST": 1, "SECOND": 2})
ordinals["THIRD"] = 3
ordinals.update({"FOURTH": 4})

ordinals
{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}

isinstance(ordinals, dict)  #False
from collections.abc import MutableMapping

class MyDict(MutableMapping):
    def __init__(self, **kwargs):
        self.data = kwargs

    def __getitem__(self, key):
        return self.data[key]

    def __delitem__(self, key):
        del self.data[key]

    def __setitem__(self, key, value):
        self.data[key] = value

    def __iter__(self):
        return iter(self.data)

    def __len__(self):
        return len(self.data)

    def __repr__(self):
        return repr(self.data)


my_dict = MyDict(a=1, b=2)
my_dict.update(c=3)
my_dict['d'] = 4
my_dict.pop('b')

my_dict   #  {'a': 1, 'c': 3, 'd': 4}

# UserDict 将整个数据结构及方法都默认实现了
# 要改哪个行为,直接覆写对应的方法就好了,很方便。
class MyDict(UserDict):
    def __setitem__(self, key, value):
        super().__setitem__(key, value * 10)


my_dict = MyDict(a=1, b=2)
my_dict   #{'a': 10, 'b': 20}
PreviousCustomizationNextLogging

Last updated 3 years ago

Was this helpful?

💕