Discuss / Python / Enum的用法の学习

Enum的用法の学习

Topic source

520bv

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-

form enum import Enum

# 第一种方法定义枚举类(继承Enum)
class colors(Enum):
    red = 1
    orange = 2
    yellow = 3
    green = 4
    blue = 5
    indigo = 6
    purple = 7
# 第二种方法(函数调用)
co = {'red':1, 'orange':2, 'yellow':3, 'green':4, 'blue':5, 'indigo':6, 'purple':7}
colours = Enum('colours', co)

# 练习
Gender = Enum('Gender', {'Male': 0, 'Female': 1})

class Student(object):
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender

# 测试:
bart = Student('Bart', Gender.Male)
if bart.gender == Gender.Male:
    print('测试通过!')
else:
    print('测试失败!')

colors.blue.value == colours.blue.value
colors is colours

Run

测试通过!
True
False

哦,原来是函数调用用了个字典{}啊,按照老师的说法类和函数其实可以视为一种。。当函数和类传入参数后就变成具体的输出和实例。然后老师用的是(),就是tuple,默认值是从1开始,这样就好理解多了


  • 1

Reply