x = getattr(self, source) will work just perfectly if source names ANY attribute of self, including the other_data in your example.
python - Access attributes of objects by string - Blender Stack Exchange
Accessing attributes of a class
how to access the class variable by string in Python? - Stack Overflow
addressing class attribute with a variable?
Videos
Is there a possibility to dynamically call class attributes based on variables?
example:
I have a class example, that has two attributes: first and second.
So you could define something like
test = example("foo", "bar") and you'd have test.first == "foo" and test.second == "bar".
Then I have another variable, say place, which is a string and is either place = "first" or place = "second".
Can I somehow call test.place?
There are a bazillion other uses for this, but at this current moment I'm trying to write a small "app" that has a few display strings, and I want to be able to select from two strings to display (two languages) based on command line argument.
Hi,
I am looking for a function in C#/Unity which allows me to get or set a variable of an instance using a string that is the same as the variable’s name.
I was using Python until recently, which does have such a function, so I want to demonstrate what I mean using that:
Let’s assume we have class called “Human”, and an instance of that class, “John”.
The class “Human” has a variable called “speed”, and “speed” variable of “John” is, for example, 10.
In Python, you can access the value ‘10’ by doing this:
getattr(John, "speed") #this would return the same value as John.speed, which is 10
Also you could set that variable to another value, like:
setattr(John, "speed", 5) #after this, John.speed or getattr(John, "speed") would return 5.
Is there a way to do this in C#/Unity?
I’m new to Unity, so although I tried to find the answer in the internet, I couldn’t find one. Can you help me?
Thanks.
setattr(my_class_instance, 'attr_name', attr_value)
After reading rejected Syntax For Dynamic Attribute Access I'm using a mixin class providing dictionary-style access to an object's attributes :
class MyClass:
def __init__(self):
self.name = None
self.text = None
def __getitem__(self, name):
return getattr(self, name)
def __setitem__(self, name, value):
return setattr(self, name, value)
def __delitem__(self, name):
return delattr(self, name)
def __contains__(self, name):
return hasattr(self, name)
While still being able to set attributes directly:
myclass = MyClass()
myclass.name = "foo"
myclass.text = "bar"
it's then possible to set them dynamically :
for attr in ('name', 'text'):
myclass[attr] = confirm(attr, default=myclass[attr])