No, Python __oct__() Doesn’t Exist Anymore. Do This Instead!

The Problem

TypeError: '...' object cannot be interpreted as an integer

If you’re reading this article, chances are that you have been thinking something along those lines:

  • Given a custom class My_Class. You want to override the behavior of the built-in oct(x) function in Python when calling it on a My_Class object x.
  • You know about the feature of Dunder Methods to overwrite the custom behavior of built-in functions.
  • You conclude that the dunder method for oct() is __oct__() because, after all, this is how it is supposed to work, right?
  • Wrong! If you try to do it, you get the following error.

The Wrong Example – Don’t!

class My_Class:
    def __oct__(self): # WRONG!
        return 42


x = My_Class()
print(oct(x))

The output indicates that something went wrong:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 7, in <module>
    print(oct(x))
TypeError: 'My_Class' object cannot be interpreted as an integer

What To Do?

How can you resolve the TypeError: 'My_Class' object cannot be interpreted as an integer?

To resolve the TypeError when trying to override the behavior of the oct() function using the __hex__() method is to forget about the __oct__() method and use the __index__() method instead.

The __index__() method returns an integer value associated with a given object. The integer is then automatically converted to an octal number.

The Right Example – Do!

Here’s how this works in a simple example:

class My_Class:
    def __index__(self): # Correct!
        return 42


x = My_Class()
print(oct(x))
# 0o52

In case you’re wondering about the output 0o52 instead of what you’ve defined, i.e., 42, the integer 42 is converted to the octal number 0o52. See here:

>>> oct(42)
'0o52'

Background oct() – Not a Magic Trick

Python’s built-in oct(integer) function takes one integer argument and returns an octal string with prefix "0o".

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!