Skip to content

Instantly share code, notes, and snippets.

@geekKeen
Created August 1, 2017 15:21
Show Gist options
  • Save geekKeen/6681d21adf53f79aeba2250ac7a6f582 to your computer and use it in GitHub Desktop.
Save geekKeen/6681d21adf53f79aeba2250ac7a6f582 to your computer and use it in GitHub Desktop.
遇到初始化时碰到的一些问题
class A(object):
def __init__(self, **config):
self._config = {}
self.make_config(config)
def make_config(config):
self._config.update(config)
class B(object):
def __init__(self, **config):
self._config = {}
self._config['a'] = config['a']
...
@geekKeen
Copy link
Author

geekKeen commented Aug 1, 2017

A 写法的好处:

  1. 完成初始化的同时,提供了可扩展性,外部有机会再此添加新配置
  2. 如果子类不想完成某些属性的初始化,可以自定义,只需要重载 make_config 就可以了; 第二种写法就没有灵活性, 因为__init__是一定会跑的,值也就没办法改变了

@geekKeen
Copy link
Author

geekKeen commented Aug 3, 2017

仔细思考后觉得这种写法,也没什么优势, 主要是 mail-sys 中 gethtml 函数没有符合单一职责的原则,函数调用有副作用, 直接插了数据,应该避免

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment