我把一堆相关的东西放进了一堂课.主要目的是将它们组织到命名空间中.
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)
Run Code Online (Sandbox Code Playgroud)
涉及的对象概念不多.在C++中,我将使用实际的语言关键字namespace.Python中没有这样的东西.所以我试图class用于此目的.
这是一个好主意吗?这种方法有任何陷阱吗?
我昨天刚回答了一个相关的问题.这个问题以不同的方式提出.这是我需要为自己做出的实际决定.
python中的静态方法与模块函数 - Stack Overflow
我有一种情况需要强制执行,并为用户提供多个select函数之一的选项,作为参数传递给另一个函数:
我真的想要实现以下内容:
from enum import Enum
#Trivial Function 1
def functionA():
pass
#Trivial Function 2
def functionB():
pass
#This is not allowed (as far as i can tell the values should be integers)
#But pseudocode for what I am after
class AvailableFunctions(Enum):
OptionA = functionA
OptionB = functionB
Run Code Online (Sandbox Code Playgroud)
所以可以执行以下操作:
def myUserFunction(theFunction = AvailableFunctions.OptionA):
#Type Check
assert isinstance(theFunction,AvailableFunctions)
#Execute the actual function held as value in the enum or equivalent
return theFunction.value()
Run Code Online (Sandbox Code Playgroud)