python again函数,python - 应该使用静态方法或顶级函数

I come from a Java background and I'm new to python. I have a couple scripts that share some helper functions unique to the application related to reading and writing files. Some functions associated with reading, some with writing. While searching for the correct approach, I saw this: Static methods in Python?

He mentions in his answer:

Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.

I don't understand top-level functions very well and I'm not sure given this simple example which is better: 1) create a class for a reader with static reader functions and the same for a writer or 2) to declare these helpers as global functions and why?

EDIT: REALLY good article about this subject i just found http://tomayko.com/writings/the-static-method-thing

解决方案

In Java there's the (IMHO wrong) idea to use classes everywhere, even just group together static functions that don't share any state (and thus such classes will never be instantiated).

Python here begs to differ; if you have functions that don't have some shared state1 (and thus in Java would typically be static functions) and aren't tightly related to a "real" class (=one that is actually instantiated) you just use free functions inside a module.

The reasoning behind this is that a class is needed only when you actually want to instantiate it, thus having a class just as a container for several functions that don't need to share an instance-specific state is useless.

Actually, you can somewhat think of a module as a static class - i.e. a container of functions (=static methods), module variables (=static fields) and types.

The nice thing in Python is that having top-level function doesn't give global namespace pollution problems, since in Python top-level functions/objects/... are still module-scoped. Thus, you can still group functions by module, without the unnecessary class-tax.

actually, they can have some shared state, in form of module-level variables (so, singletons); again, the analogy modules-static classes seems to hold.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值