0

I've encountered a question on a course in oop in python regarding bin(). The author wanted to modify it in such a way that it would return the binary representation of a number in a different format.

For example, bin(30), instead of '0b11110' would output '00011110'. This can be done, for instance, by a workaround

bin(30)[2:].zfill(8)

According to the documentary and this stack question, this can be done also by

f'{30:08b}'

Is there a smart way to define a class to do just that? Note, a beginner here. Here's my attempt:

class my_bin(object):
    def __init__(self,value):
        self.binary = format(value, '08b')

    def __repr__(self):
        return str(self.binary)
Grzegorz Rut
  • 205
  • 1
  • 2
  • 8
  • Why write a class? `bin` is a function, just write another function that implements the workaround. – jonrsharpe Jun 20 '18 at 16:07
  • 2
    No, why would you need to use class? You are not keeping state. You can trivially create a function instead: `my_bin = lambda v: f'{v:08b}'` and know it'll always return a string. – Martijn Pieters Jun 20 '18 at 16:07
  • it's just a question from a user of an online course. I agree, a function should be enough. – Grzegorz Rut Jun 20 '18 at 16:10
  • for a class you can write your own __format__ method - so that would allow you to write your own formatting syntax for your binary values : https://docs.python.org/3/reference/datamodel.html#basic-customization – Tony Suffolk 66 Jun 24 '18 at 10:12

0 Answers0