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
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.
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.