查询从Enum继承

时间:2019-07-16 00:15:11

标签: python python-3.x

我是python的初学者,遇到了这样的问题。当我尝试创建自己的类(它是子类)时,遇到了这样的错误:

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    class gender(Enum):
  File "C:\Program Files (x86)\Python365_64bit\lib\enum.py", line 208, in __new__
    enum_member.__init__(*args)
TypeError: __init__() takes 1 positional argument but 2 were given

我上的课是:

class gender(Enum):
    Male = 0
    Female = 1

    def __init__(self):
        if self.value == 0:
            self.sex = 'Boy'
        else:
            self.sex = 'Girl'

    def getsex(self):
        print('This person is ',self.sex)

只想知道为什么__init__不起作用....

1 个答案:

答案 0 :(得分:0)

您将错误数量的参数传递给__init__,有关__init__() takes 1 positional argument but 2 were given错误的信息,请参见this post

我已经像这样修改了您的代码。看看这是否适合您。

from enum import Enum

class Gender(Enum):
    Male = 0
    Female = 1
    sex = ''

    def __init__(self, value):
        if value == 0:
            self.sex = 'Boy'
        else:
            self.sex = 'Girl'

    def getsex(self):
        print('This person is ',self.sex)


# The following is how I use the class:

g = Gender(Gender.Female)
g.getsex()

value中的def __init__(self, value):代表我传入的参数Gender.Female

self中的def __init__(self, value):代表Gender的实例。

当我调用Gender(Gender.Female)时,python在后台调用__init__(self, Gender.Female)。这就是将新参数value添加到__init__的原因。