相关疑难解决方法(0)

Python,Enum类型的优点是什么?

在Python 3.4中,我们在标准库中获得了一个Enum lib : enum. 我们可以enum使用Python 2.4到2.7(甚至3.1到3.3),pypi中的enum34来获得一个后端.

但是,如果没有这个新模块,我们已经相处了很长一段时间 - 那么为什么我们现在拥有它呢?

我对其他语言的枚举目的有一个大概的了解.在Python中,通常使用如下的裸类并将其称为枚举:

class Colors:
    blue = 1
    green = 2
    red = 3
Run Code Online (Sandbox Code Playgroud)

这可以在API中用于创建值的规范表示,例如:

function_of_color(Colors.green)
Run Code Online (Sandbox Code Playgroud)

如果这有任何批评,它是可变的,你不能迭代它(很容易),我们如何知道整数的语义2

那么我想我可以使用像namedtuple这样的东西,它是不可变的?

>>> Colors = namedtuple('Colors', 'blue green red')
>>> colors = Colors('blue', 'green', 'red')
>>> colors
Colors(blue='blue', green='green', red='red')
>>> list(colors)
['blue', 'green', 'red']
>>> len(colors)
3
>>> colors.blue
'blue'
>>> colors.index(colors.blue)
0
Run Code Online (Sandbox Code Playgroud)

namedtuple的创建有点多余(我们必须将每个名称写两次),因此有点不优雅.获得颜色的"数字"也有点不优雅(我们必须写colors两次).必须使用字符串进行值检查,效率稍低.

所以回到枚举.

枚举的目的是什么?他们为语言创造了什么价值?我何时应该使用它们,何时应该避免使用它们?

python enums

35
推荐指数
1
解决办法
2万
查看次数

TypeScript:为什么不强制使用确切的枚举类型?

请看一下这个简单的代码:

const enum MyEnum {
    Zero
} 

const foo: MyEnum.Zero = 0 // OK as expected (since MyEnum.Zero is zero)
const bar: MyEnum.Zero = 1 // OK, but expected Error! Why?
Run Code Online (Sandbox Code Playgroud)

0在这种情况下,如何执行精确的窄数类型?

操场

UPD:枚举似乎已损坏https://github.com/microsoft/TypeScript/issues/11559

typescript

6
推荐指数
1
解决办法
70
查看次数

为什么字符串文字与枚举不匹配

我试图在打字稿中使用枚举,但它们的类型检查似乎不太一致。为什么我可以TestEnum.Foo === 'foo'在没有警告的情况下进行检查,但尝试传递'foo'到接受 a 的函数TestEnum会导致错误。

describe('Test enum functionality', () => {
  enum TestEnum {
    Foo = 'foo',
    Bar = 'bar'
  }

  // I expected this to work as TestEnum.Foo === 'foo'
  test('Can pass string to enum', () => {
    const func = (x: TestEnum) => {}
    // Error: Argument of type '"foo"' is not assignable to parameter of type 'TestEnum'
    func('foo');
  });

  // Surprised that this worked after I couldn't pass in a string …
Run Code Online (Sandbox Code Playgroud)

enums typescript

0
推荐指数
1
解决办法
2046
查看次数

标签 统计

enums ×2

typescript ×2

python ×1