papay
papay

Reputation: 1

how can i refer to instance name in the class?

in this code:

class X:
    def __init__(self, y=None):
        self.y = y
        self.z = []
        try:
            y.z.append(self)
        except:
            pass

a = X()
b = X(a)
c = X(a)

print(a.z)

I want to print [b, c] but it prints something like this

out: <__main__.x object at 0x01775E70>, <__main__.x object at 0x01775E90>]

how i can fix it?

Upvotes: 0

Views: 62

Answers (2)

timgeb
timgeb

Reputation: 78780

Impossible*. Names refer to values unidirectionally. You cannot go from a value to a name. Consider many names refering to the same value, e.g. a = b = 1. What would be the true name of the value 1? There is none, all names are equal.

*without inspecting the source code. And as I said, what should happen to how a.z is displayed if you then assign c = b? What you are trying to do is fruitless and if you really need it you have a design issue.

Upvotes: 1

Yassine Faris
Yassine Faris

Reputation: 991

If you want print to display a text for an object, you need to implement the __str__ method:

class X:
    def __init__(self, name, y=None):
        self.name = name
        self.y = y
        self.z = []
        try:
            y.z.append(self)
        except:
            pass

    def __repr__(self):
        return self.name


a = X("a")
b = X("b", a)
c = X("c", a)

print(a.z)

Or did you want print to use the name of the reference of the object?

Upvotes: 0

Related Questions