简体   繁体   中英

Use class instance names as legend entry for e.g. a plot

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

If you will to pass the variable name as argument for plotting, then you can use f-strings:

>>> myvar = object()
>>> myvar2 = 6
>>> print(f"{myvar=} {myvar2=}")
myvar=<object object at 0x7f32b650c850> myvar2=6

So you can split at the equal sign and keep the variable name:

>>> myvar = object()
>>> print(f"{myvar=}".split('=')[0])
myvar

Then you can use that the way you want whether you print it or send it into another function.

From this comment .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM