0

Background

I have a new feature to implement in my code and it can be solved by reasign a variable without change the pointer to memory.

a = "hi"
print(hex(id(a)))
a = "bye"
print(hex(id(a)))

DESIRED OUTPUT:
0x7fec363cd4f0
0x7fec363cd4f0

REAL OUTPUT:
0x7fec363cd4f0
0x7fec363cd530

Problem

It can't be done in Python from what I've read. So, I think to create a class that inherit from str and implement a method that update the value. That is because after updating it, pointer to memory does not change. But Im stack.

Question

I have created a custom string class that inherit from str:

class MyStr(str):
def __new__(cls, s):
    return super().__new__(cls, s)

def __init__(self, s):
    super().__init__()

If I create a object of this class and print it, the output is:

print(MyStr("hi"))
hi

What I want now, is to create a method in MyStr that update "value of the string" and have by output:

my_str = MyStr("hi")
my_str.update_value("bye")

print(my_str)
bye

How update_value method must be?

Further work

In addition, I would like to do this for int and float.

Thanks in advance

  • 3
    `a` doesn't have an address in memory; it's just a name ("pointer", if you will) for an arbitrary object. The object has a unique id (which in CPython is typically the memory address of the *object*), but it is an implementation detail whether *literals* will generate a new object or reuse an existing object. – chepner May 13 '21 at 11:55
  • You probably want a custom `__str__` method to return the value of the attribute. Note that there is no compelling reason to subclass `str` here, as you simply want a *wrapper* around a `str` value. – chepner May 13 '21 at 11:56
  • 1
    "I have a new feature to implement in my code and it can be solved by reasign a variable without change the pointer to memory." I think you are fundamentally confused, *Python doesn't have pointers*. – juanpa.arrivillaga May 13 '21 at 11:57
  • 1
    There *are no methods* that mutate `str`, `int` or `float` objects, by definition, because *they are immutable*. It sounds like you just want a *wrapper* for these objects. IOW, you don't need inheritance, you need *composition*. – juanpa.arrivillaga May 13 '21 at 11:59
  • and if you are trying to make something like optimised strings, I will let you know the automatic garbage collection is well enough to handle new string and deleting old strings. and as others have pointed out, these objects can not be inherited. – AmaanK May 13 '21 at 12:00

0 Answers0