0

I am a beginner of python and I came across such a problem. When I tried to create my own class, which is a subclass, I came across such error:

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

The class I made is:

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)

Just want to know why __init__ is not working ....

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Tyler Parker
  • 81
  • 1
  • 4

1 Answers1

0

You passed wrong number of arguments to __init__, see this post for information about __init__() takes 1 positional argument but 2 were given error.

I've modified your code like this. See if this fits you.

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()

The value in def __init__(self, value): represents the parameter,Gender.Female I passed in.

The self in def __init__(self, value): represents the instance of Gender.

When I call Gender(Gender.Female), python calls __init__(self, Gender.Female) behind the scenes. That's the reason for adding the new argument value to __init__.

Brian
  • 12,145
  • 20
  • 90
  • 153