我将一堆相关的东西放到一个类中.主要目的是将它们组织成一个命名空间.
I am putting a bunch of related stuff into a class. The main purpose is to organize them into a namespace.
class Direction:
north = 0
east = 1
south = 2
west = 3
@staticmethod
def turn_right(d):
return turn_to_the_right
@staticmethod
def turn_left(d):
return turn_to_the_left
# defined a short alias because direction will be used a lot
D = Direction
d0 = D.north
d1 = D.turn_right(d)
涉及的对象概念并不多.在 C++ 中,我将使用实际的语言关键字 namespace
.Python中没有这样的东西.所以我试图使用 class
来达到这个目的.
There is not much object concept involved. In C++, I will be using the actual language keyword namespace
. There is no such thing in Python. So I am trying to use class
for this purpose.
这是个好主意吗?这种方法有什么陷阱吗?
Is this a good idea? Any pitfall with this approach?
我昨天刚刚回答了一个相关问题.这个问题以不同的方式提出.这是我需要为自己做出的实际决定.
I've just answer a related question yesterday. This question is asked in a different way. It is an actual decision I need to make for myself.
python中的静态方法与模块函数 - 代码日志
Static method vs module function in python - Stack Overflow
python中的静态方法与模块函数
是的,确实.您可以将 Python 类严格用于命名空间,因为这是它们可以做的特殊事情之一,并且与模块不同.在文件中将类定义为内联命名空间比生成更多文件要容易得多.你不应该在没有评论你的代码说明它的用途的情况下这样做.Python 类有很多不同的形式和用途,这让您难以理解以前从未见过的代码.
Yes, indeed. You can use Python classes strictly for namespacing as that is one of the special things they can do and do differently than modules. It's a lot easier to define a class as a namespace inline in a file than to generate more files. You should not do it without commenting your code saying what it's for. Python classes come in a lot of different forms and purposes and this makes difficulty understanding code you have not seen before.
用作命名空间的 Python 类不亚于 Python 类,它满足对其他语言中类的理解.Python 不需要实例化一个类就可以使用.它不需要 ivars 也不需要方法.它相当灵活.
A Python class used as a namespace is no less a Python class than one that meets the perception of what a class is in other languages. Python does not require a class to be instantiated to be useful. It does not require ivars and does not require methods. It is fairly flexible.
类也可以包含其他类.
很多人对什么是 Pythonic 或不是 Pythonic 都有自己的想法.但是如果他们都担心一致性之类的东西,他们会推动拥有像 len()
dir()
和 help()
这样的东西是对象的方法而不是全局函数.
Lots of people have their ideas about what is or isn't Pythonic.
But if they were all worried about something like consistency, they'd push to have things like len()
dir()
and help()
be a method of objects rather than a global function.
做有效的事,如果不常用或不明显的用法,请对其进行评论/记录.
Do what works, comment / document it if it isn't usual or obvious usage.
这篇关于在 Python 中使用类作为命名空间是个好主意吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!