Skip to content

Instantly share code, notes, and snippets.

@ahmedsakr
Created August 3, 2020 04:16
Show Gist options
  • Save ahmedsakr/ad227860b3e2f52bcbfc241644d4d1ee to your computer and use it in GitHub Desktop.
Save ahmedsakr/ad227860b3e2f52bcbfc241644d4d1ee to your computer and use it in GitHub Desktop.
A class that extends the immutable tuple
class NumberTuple(tuple):
'''
NumberTuple is a tuple class that wishes to convert
string number to a tuple.
'''
def __init__(self, number):
'''
While our goal is to convert the string number
to a tuple, we cannot reassign the NumberTuple object
in the __init__ function - since it's already been created,
and it's immutable.
'''
pass
def __new__(cls, number):
'''
This is where __new__ comes to the rescue: this is invoked
before the tuple object is created. We interject, converting
the number from a string to a tuple, and then finally
tell python to use the tuple value we created!
'''
if isinstance(number, str):
number = tuple(number)
return super(NumberTuple, cls).__new__(cls, number)
# output: ('1', '2', '4' )
print(NumberTuple('124'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment