我想使用枚举来表示类的内部状态:
#!/usr/bin/python3
from enum import Enum
class testClass:
class Color(Enum):
red = 1
blue = 2
green = 3
def __init__(self):
self.value = 0
def setValue(self, Color):
self.value = Color
Run Code Online (Sandbox Code Playgroud)
这就是我认为可能的实施方案。我看到的两件烦人的事情是:
要设置value我必须做:
q = testClass()
q.setValue(q.Color.red)
我觉得这q.Color.red有点令人不快,我宁愿有类似的东西:Color.red或者只是red。也许唯一的方法是使用一些字符串比较,但这正是我试图避免使用枚举的。
我得到了一个额外的方法,q.Color.mro它看起来像是枚举类的内部方法。这个是来做什么的?
作为练习,我试图衡量应该执行相同任务的两种算法的效率,即仅使用堆栈作为支持数据结构,对堆栈进行排序:
#include <stack>
#include <iostream>
#include <chrono>
std::stack<int> sortStack(std::stack<int>& inS){
std::stack<int> tmpS;
int tmpV=0;
tmpS.push(inS.top());
inS.pop();
while(!inS.empty()){
if(inS.top()>=tmpS.top()){
tmpS.push(inS.top());
inS.pop();
}else{
tmpV = inS.top();
inS.pop();
int count = 0;
//reverse the stack until we find the item that is smaller
while(!tmpS.empty()){
if(tmpS.top()>tmpV){
inS.push(tmpS.top());
tmpS.pop();
count++;
}else{
break;
}
}
//tmpS.top is smaller (or =) than tmpV
tmpS.push(tmpV);
//and revert the other stack
for(int i=0; i< count; i++){
tmpS.push(inS.top());
inS.pop();
}
}
}
return tmpS;
}
std::stack<int> sortStackRevisited(std::stack<int>& inS){
std::stack<int> tmpS; …Run Code Online (Sandbox Code Playgroud)