Oct() Function In Python

Function Name:



Function Signature:



Function Overview:

The python function oct() converts an integer value of 

  • Decimal format
  • Hexa-decimal format
  • Octal format

into octal format and returns the string that contains the octal form.


As long as __index__() method is defined for a python object - the oct() function will convert the integer returned by the __index__() method into the octal form.



# A class that defines the __inedx__() method

class SpecialClass:

    def __init__(self, val):

        self.myVal = val


    def __index__(self):

        return self.myVal


# Convert decimal form to octal form

decimalNumber   = 33

octalString     = oct(decimalNumber)

print("Decimal form to Octal form:{}".format(octalString))


# Convert hexa-decimal form to octal form

hexaDecimalNumber   = 0x33F

octalString         = oct(hexaDecimalNumber)

print("Hexa-decimal form to Octal form:{}".format(octalString))


# Convert an object that has the __index__() implemented

numericObject       = SpecialClass(33)

octalString         = oct(numericObject)

print("Object with __index__() to Octal form:{}".format(octalString))




Decimal form to Octal form:0o41

Hexa-decimal form to Octal form:0o1477

Object with __index__() to Octal form:0o41


Copyright 2022 © pythontic.com