How to Reference an Object Within Itself Without Modifying the Class?

0
3
Asked By CuriousCoder92 On

I'm working with a class called `Uwu` in Python (though this could apply to any OOP language). The class has a constructor that requires an argument `owo`. Here's the class code:

```python
class Uwu:
def __init__(self, owo):
self._owo = owo
def getOwo(self):
return self._owo
```

My question is, how can I create an instance of `Uwu` such that `uwuA.getOwo() == uwuA` or even that `uwuA.getOwo() == uwuB` and `uwuB.getOwo() == uwuA`? Ideally, I want to achieve this without making any changes to the `Uwu` class itself. I'm looking for a neat solution, so any suggestions would be appreciated!

1 Answer

Answered By TechieTom On

Creating a reference cycle without altering the class structure is pretty tricky. Typically, constructors expect all values to be initialized at creation. One common workaround is to use a setter method like this:

```python
class Uwu:
def __init__(self, owo=None):
self._owo = owo
def getOwo(self):
return self._owo
def setOwo(self, owo):
self._owo = owo
```

You would create an instance and then call the setter:

```python
uwuA = Uwu()
uwuA.setOwo(uwuA)
```

I get that you’re trying to avoid modifying the class, but this is generally the best practice. Alternatively, you could manipulate references like this:

```python
class Uwu:
def __init__(self, owo):
self._owo = owo

cache = []
uwuA = Uwu(cache)
cache.append(uwuA)
```

And if you absolutely must stick to pointers, you could look into that, but it’s not the cleanest approach.

SkepticalSam -

But isn’t the essence of pointers to do exactly what you mentioned? I could just pass all the pointers in an array and set them afterward.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.