源码中这个场景,用 staticmethod 有很大的必要性吗?

2019-01-10 16:56:46 +08:00
 firejoke

基类:

class Schema(object):

......

    def filter(self, obj):
        filtered = {}
        for key, value in six.iteritems(obj):
            if self._filter_func(self.properties, key):
                filtered[key] = value

......

    @staticmethod
    def _filter_func(properties, key):
        return key in properties

其中一个重写了该方法的子类:

class PermissiveSchema(Schema):
    @staticmethod
    def _filter_func(properties, key):
        return True

感觉上完全不需要改成 staticmethod
反正最终还是需要传类的属性进去

1304 次点击
所在节点    Python
2 条回复
xpresslink
2019-01-10 17:16:09 +08:00
完全没有必要,python 中 staticmethod 很少用到,只是当成类的不同工厂函数时候用一下的情况比较多。
firejoke
2019-01-10 17:35:01 +08:00
@xpresslink 我也是觉得完全不必改成 staticmethod, 但源码中大量的工厂和抽象工厂,ABC 基类到处飞,
让我深深怀疑自己没有坐着考虑的深,不敢去质疑作者......

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/525745

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX