【Python】定义结构体,没有结构体,只能定义一个类

Python中没有专门定义结构体的方法,类似于C++,可以使用class标记定义类来代替结构体,其成员可以在构造函数__init__中定义,具体方法如下:

   class item:
        def __init__(self):
            self.name = ''     
            self.size = 10     
            self.list = []     

    a = item() # 定义结构对象
    a.name = 'cup'
    a.size = 8
    a.list.append('water')

每次定义一个对象的时候init函数对其进行了一次初始化。

原文链接:https://blog.csdn.net/m0_37362454/article/details/82145146

枚举:

import os
import sys
if sys.version_info.major + sys.version_info.minor * 0.1 < 3.4:
    from enum34 import Enum
else:
    from enum import Enum

class MyColorEnum(Enum):
    red = 1
    red_alias = 1
    blue = 2
    green = 'green'

MyColorEnum.red.name    # get member name string
MyColorEnum.red.value   # get member value

for c in MyColorEnum:
    print(c)    # just one of MyColorEnum.red_alias and MyColorEnum.red, according to the order which itself decides

for c in MyColorEnum.__members__.items():
    c[0]    # str name eg. 'red'
    c[1]    # member eg. MyColorEnum.red
    # contain 'red_alias' and MyColorEnum.red_alias

'red' in MyColorEnum.__members__    # if member name in Enum
0 in MyColorEnum._value2member_map_ # if value in Enum values

MyColorEnum.__members__['red']  # MyColorEnum.red, get member by member name string, if no such member name string, raising KeyError

# comparation ################################################################################
MyColorEnum.red is MyColorEnum.red_alias    # True
MyColorEnum.red == MyColorEnum.red_alias    # True
MyColorEnum.red != MyColorEnum.red_alias    # False
#never do this
#MyColorEnum.red < MyColorEnum.blue  # raising TypeError, Enum values could be different types

原文:https://www.cnblogs.com/ibingshan/p/10375643.html

posted @ 2020-07-13 14:06  瘋耔  阅读(2376)  评论(0编辑  收藏  举报
跳至侧栏