假设当前代码使用字符串作为参数,并且您希望记录它们的有效值.
例
def MyFunc(region = None):
if region in ['A','B','C', None]:
# dosomething
else:
# complain about invalid parameter
Run Code Online (Sandbox Code Playgroud)
现在的问题是如何改进这个设计以解决两个问题:
能够使用IDE中的自动完成功能自动完成参数的可能值.
记录参数的有效值列表(目前使用doxygen记录代码)
我有一个函数,它有几个可能的返回值。作为一个简单的例子,让我们假设它接受一个正整数并返回“小”、“中”或“大”:
def size(x):
if x < 10:
return SMALL
if x < 20:
return MEDIUM
return LARGE
Run Code Online (Sandbox Code Playgroud)
我想知道编写和定义返回值的最佳方法。我想知道使用Python函数属性,如下:
def size(x):
if x < 10:
return size.small
if x < 20:
return size.medium
return size.large
size.small = 1
size.medium = 2
size.large = 3
Run Code Online (Sandbox Code Playgroud)
然后我的调用代码看起来像:
if size(n) == size.small:
...
Run Code Online (Sandbox Code Playgroud)
这似乎是一个不错的内置“枚举”,可能比创建模块级枚举或将 3 个值定义为全局常量(如SIZE_SMALL, SIZE_MEDIUM等)更清晰/更简单。但我认为我以前从未见过这样的代码. 这是一个好方法还是有陷阱/缺点?
我正在为大学做一个python跳棋游戏.我使用tk绘制了电路板,但我似乎无法为这些部件实现移动功能.如果有人在我的代码中看到任何错误,或者可以提供帮助,我将不胜感激.这是完整的来源.提前致谢.
我知道这会吸引棋子.我不知道如何重新绘制碎片,而不删除其他碎片.我已经在线查看了移动功能,并尝试了简单的测试,但我无法在我的代码中使用它.
lst2 = []
#counter variable
i=0
#board variable is what stores the X/O/- values.
# It's a 2D list. We iterate over it, looking to see
# if there is a value that is X or O. If so, we draw
# text to the screen in the appropriate spot (based on
# i and j.
while i < len(board):
j=0
while j < len(board[i]):
if board[i][j] == 2:
lst2.append(canvas.create_oval((i+1)*width + width/2 + 15,
(j+1)*height + height/2 …Run Code Online (Sandbox Code Playgroud) 我搜索过并搜索过,但是我还没有找到一个能够做我需要做的事情的例子.
我发现
如何用Python代表'Enum'?
这里是SO,但它不包括ctypes.Structure.我还在
SO上找到了
在ctypes.Structure中使用枚举,但它包含了我不熟悉的指针.
我有一个包含typedef枚举的头文件,我需要在Python文件中的ctypes.Structure中使用它.
C++头文件:
typedef enum {
ID_UNUSED,
ID_DEVICE_NAME,
ID_SCSI,
ID_DEVICE_NUM,
} id_type_et;
Run Code Online (Sandbox Code Playgroud)
Python文件(我目前的方式):
class IdTypeEt(ctypes.Structure):
_pack_ = 1
_fields_ = [ ("ID_UNUSED", ctypes.c_int32),
("ID_DEVICE_NAME", ctypes.c_char*64),
("ID_SCSI", ctypes.c_int32),
("ID_DEVICE_NUM", ctypes.c_int32) ]
Run Code Online (Sandbox Code Playgroud)
任何建议将不胜感激.越简单越好.
以下哪两种方法被认为是最佳实践?两者都达到相同的结果。
class Foo():
LABELS = ('One','Two','Three')
class Bar():
def __init__(self):
self.__labels = ('One','Two','Three')
@property
def labels(self):
return self.__labels
Run Code Online (Sandbox Code Playgroud) 我非常喜欢 Enum 并且我想做以下事情:
class Color(Enum):
green = 0
red = 1
blue = 1
for color in Color:
print(color.name)
print(color.value)
Run Code Online (Sandbox Code Playgroud)
如您所见,Color 类中有重复的值。在这种情况下,我可以使用什么类替代方案来支持可迭代、名称、值?
我想初始化一个User具有属性的类,其值取自一组有限且不可变的可能值(例如,用户类型、国家/地区的简短列表......)。在 Python 中做到这一点的最佳方法是什么?
class User(object):
def __init__(self, type, country):
self.type = type # Possible values: [Consumer, Producer]
self.country = country # Possible values: [UK, USA, Japan, France]
Run Code Online (Sandbox Code Playgroud)
这可能是显而易见的,但我正式限制这组可能值的原因主要是为了避免/发现错误。
我已经查看了 Python上list和EnumPython中的各种解释(例如,如何在 Python 中实现枚举),但我不确定考虑到我的需求,这是否是正确的方法。特别是,从我读过的内容来看,似乎Enum是存储一个常量列表(User.typeasCONSUMER和PRODUCER)......但我希望能够直接在输出中使用这些值(所以大写看起来很奇怪)。而且我不确定每个值是否有等价的数字(CONSUMER=1 ...) 的对我有用。
编辑:我可能应该补充一点,我的应用程序中的实际值是法语,因此包括非 ASCII 字符(例如,États-Unis)。走这Enum条路似乎无法保留这些字符,并且意味着然后将值“转换”为“本地化”值,这在我看来对于一个简短的列表来说很麻烦。
我在可重用的类中有一些代码可以修改某些类型.这是一个简化版本.
class Foo:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
# Add another method outside of the class definition.
# Pylint doesn't care about this, and rates this file 10/10.
Foo.__dict__["current_count"] = lambda self: self.count
Run Code Online (Sandbox Code Playgroud)
在实际代码中,"current_count"是一个变量,而不是一个固定的字符串,这就是为什么我没有写:
Foo.current_count = lambda self: self.count # Cannot do in my scenario.
Run Code Online (Sandbox Code Playgroud)
现在,当我的客户来使用新功能时,Pylint惊恐地跳起来.
import server_api
def main():
foo_count = server_api.Foo()
foo_count.increment()
print foo_count.current_count()
# Pylint complains here:
# E1101: 8:main: Instance of 'Foo' has no 'current_count' member
# I don't want to …Run Code Online (Sandbox Code Playgroud) 我从这个代码片段开始,根据我的理解,它实际上是一个类别工厂,可以模拟其他语言的"枚举"类型:
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
Run Code Online (Sandbox Code Playgroud)
(我从这里拿走:我如何在Python中表示'Enum'?)
我知道它是如何工作的,它确实如此,但是我想让我的动态生成的类,类型为'Enum',可迭代,以便我可以执行以下操作以进行完整性检查:
MyEnum = enum('FOO', 'BAR', 'JIMMY')
def func(my_enum_value): # expects one of the MyEnum values
if not my_enum_value in MyEnum:
raise SomeSortOfException
Run Code Online (Sandbox Code Playgroud)
但是,为了使完整性检查工作,我需要使MyEnum可迭代.我读到这里:http://pydanny.blogspot.com/2007/10/required-methods-to-make-class-iterable.html,我需要添加ITER LEN 包含和的GetItem方法来东西,以使其可迭代.我开始走这条路(改写枚举代码)但被卡住了:
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
enums['_enums'] = enums.copy() # (so I'd have them in the Class in order to use for the methods I'll be implementing to make it iterable) …Run Code Online (Sandbox Code Playgroud) 我发现如何在Python中表示"Enum"?如何在python中创建枚举.我有一个字段ndb.Model,我想接受我的一个枚举值.我只是将字段设置为StringProperty?我的枚举是
def enum(**enums):
return type('Enum', (), enums)
ALPHA = enum(A="A", B="B", C="C", D="D")
Run Code Online (Sandbox Code Playgroud)