Skip to content Skip to sidebar Skip to footer

How To Use Setattr If Value Is Not Single?

I want to use setattr to create a plot: import numpy as np import matplotlib.pyplot as plt x = np.random.rand(10) y = np.random.rand(10) # I want this: #

Solution 1:

I think what you are looking for is getattr. In this case, it will return a Callable, so you can just treat it like a function, like this:

getattr(plt, 'scatter')(x, y)

Is the same as this:

plt.scatter(x, y)

Using setattr in that way would be more akin to plt.scatter = (x, y), which I don't think is what you want to do.

Solution 2:

You're not setting an attribute, but instead calling one.

getattr(plt, some_func)(x, y)

will call

plt.some_func(x, y)

So, in your case, you want to run

getattr(plt, 'scatter')(x, y)

Post a Comment for "How To Use Setattr If Value Is Not Single?"