0

Say that I have defined a class and I make a couple of instances of it:

A = MyClass()
B = MyClass()

Assume now that I defined a my_plot function that takes instances of classes MyClass as input, e.g. I have something like the following:

def my_plot(X,Y):
    # Do something and plot
    plt.legend([?,??])

that I can call with my_plot(A,B).

I wish to replace the ? and the ?? in the line plt.legend([?,??]) of the pseudo-code snippet above with with A and B, respectively. So far, a way to circumnavigate the problem is to equip the MyClass with an attribute name and do something like this

A = MyClass('nameA')
B = MyClass('nameB')

and then

def my_plot(X,Y):
    # Do something
    plt.legend([X.name,Y.name])

but I found boring to to instantiate a class with A = MyClass('nameA'), B = MyClass('nameB'). I wish to instantiate my classes with A = MyClass(), B = MyClass() and retrieve the instances names for the plot inside the my_plot function.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Barzi2001
  • 989
  • 8
  • 24
  • 1
    You should read e.g. https://nedbatchelder.com/text/names.html - names are _labels_, the identifiers (whether none, one or many) to which they're assigned are not properties of the instances. Maybe use a _dictionary_, then you can use the key (name) and the value (instance)? – jonrsharpe Jul 20 '22 at 15:49
  • `d = {'A': MyClass(), 'B': MyClass()}`. Now `d['A']` and `d['B']` are your references, not `A` and `B`. More importantly, the names are now *data*, not code, and can be passed into `my_plot`. – chepner Jul 20 '22 at 15:53

0 Answers0