問題描述
我將一堆相關的東西放到一個類中.主要目的是將它們組織成一個命名空間.
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中的靜態(tài)方法與模塊函數(shù) - 代碼日志
Static method vs module function in python - Stack Overflow
python中的靜態(tài)方法與模塊函數(shù)
推薦答案
是的,確實.您可以將 Python 類嚴格用于命名空間,因為這是它們可以做的特殊事情之一,并且與模塊不同.在文件中將類定義為內(nèi)聯(lián)命名空間比生成更多文件要容易得多.你不應該在沒有評論你的代碼說明它的用途的情況下這樣做.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()
這樣的東西是對象的方法而不是全局函數(shù).
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模板網(wǎng)!