1

I'm creating a hex class for hexadecimal values. The __init__ method is expecting a hex string, but I want to be able to create a Hex instance from an integer in decimal, so I create a method for that. The code is as follows:

class Hex:

    def __init__(self, val):
        #val should be a hex string
        self.val = val

    def from_dec(self, x):
        self.__init__(self, hex(x))

However, when I run:

a = Hex.from_dec(20)
print a.val

I get the following error:

TypeError: unbound method from_dec() must be called with Hex instance 
as first argument (got int instance instead)

How do I use __init__ properly?

Alasdair
  • 298,606
  • 55
  • 578
  • 516
DarkPotatoKing
  • 499
  • 2
  • 9
  • 17

3 Answers3

2

The first argument of your method from_dec is self, which means that an object of the class Hex is expected.

I would create a method outside the class to create hex objects from a decimal input.

def from_dec(x):
    return Hex(hex(x))

class Hex:

    def __init__(self, val):
        #val should be a hex string
        self.val = val

Or change the input arguments of the constructor.

class Hex:

    def __init__(self, val, dec=False):
        #val should be a hex string, unless dec=True
        if dec:
            self.val = hex(val)
        else:
            self.val = val

h = Hex(20, dec=True)
physicalattraction
  • 6,485
  • 10
  • 63
  • 122
2

One fairly idiomatic way would be to make from_dec a classmethod:

class Hex:

    def __init__(self, val):
        #val should be a hex string
        self.val = val

    @classmethod
    def from_int(cls, x):
        return(Hex(hex(x)))

print Hex('0xab').val
print Hex.from_int(99).val
bsa
  • 2,671
  • 21
  • 31
0

When calling class' function do NOT include first parameter (read python doc about classes!).

this is going to work properly:

def from_dec(self, x):
    self.__init__(hex(x))

however, it's going to be better to assign to variable, not to use init, which should be run only during initialization of object.

def from_dec(self, x):
    self.val = hex(self.val)
sokoli
  • 501
  • 3
  • 10
  • the former still does not work, gives the same error: TypeError: unbound method from_dec() must be called with Hex instance as first argument (got int instance instead) – DarkPotatoKing Jan 14 '15 at 09:21
  • oh, sorry, you need firstly to create your class and then call from_dec using class. or use @classmethod, as shown by bsa – sokoli Jan 14 '15 at 10:03