python中的静态方法与模块功能 [英] Static method vs module function in python

查看:99
本文介绍了python中的静态方法与模块功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在一个具有一些静态方法的模块中有一个类.这些静态方法中的几个仅用于crc检查和填充,它们在类之外并没有真正的用处(我只是将它们设置为Java或C ++中的私有静态方法).我想知道是否应该使它们成为全局类函数(在类外部).

So I have a class in a module that has some static methods. A couple of these static methods just do crc checks and stuff, and they're not really useful outside of the class (I would just make them private static methods in java or C++). I'm wondering if I should instead make them global class functions (outside of the class).

以任何一种方式进行操作有没有好处?该类是由from module import class导入的,因此我也不担心将这些模块也插入.但是我应该让它们成为类方法,以使from module import *更安全吗?

Is there any benefit for doing it either way? The class is being imported by from module import class so I'm not worried about having those modules pulled in as well. But should I just make them class methods so that from module import * is safer or something?

推荐答案

使用单个下划线给函数名称加上前缀是一种惯例,即它们是私有的,并且还可以防止它们使用from module import *导入.

Prefixing the function names with a single underscore is a convention to say that they are private, and it will also prevent them from being imported with a from module import *.

另一种技术是指定 __all__ 模块中的列表-这可以在模块本身中完成(您不需要__init__.py文件)

Another technique is to specify an __all__ list in the module - this can just be done in the module itself (you don't need an __init__.py file)

__all__ = ['my_class_name']

这更像是一种白名单方法,因此您可以完全控制导入的内容,而无需使用前划线.

This is more of a whitelist approach, so you can have full control over what gets imported without using leading underscores.

因此,除非您的方法在逻辑上属于该类,并且从您的描述不属于此类,否则我将其保留为模块级功能,并使用这两种方法之一将它们设为私有.

So unless your methods logically belong in the class, and from your description they don't, I would leave them as module level functions and use one of these two approaches to make them private.

这篇关于python中的静态方法与模块功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆