Reputation: 135
In Python, I am trying to create a class that has attributes which I can "get" (sorry if this wording is not exactly correct).
Basically I am trying to define some class p which has attributes var1
and var2
. So then I can use p.get("var1")
and p.get("var2")
to get the values of these respective attributes. How can I define something like this?
Upvotes: 0
Views: 680
Reputation: 8558
You can define a class with get()
method and check if the instance has the attribute with built-in getattr()
method as following:
class MyClass:
def get(self, property, default=None):
return getattr(self, property, default)
var1 = 'var1'
var2 = 'var2'
myInstance = MyClass()
print(myInstance.get('var1'))
print(myInstance.get('var3', 'NonExisting Attribute'))
Here's a working repl.it project that I just created: https://repl.it/@HarunYlmaz/OvalLiveMethod
You can also check if the instance has the attribute with hasattr()
method:
class MyClass:
def get(self, property, default=None):
if hasattr(self, property):
return getattr(self, property)
else:
return default
# Or you can raise an exception here
Upvotes: 1
Reputation: 169
class Test:
def __init__(self):
self.a = 1
self.b = 2
def get(self, var):
return eval('self.%s' % var)
t = Test()
a = t.get('a')
print(a) ## output: 1
class Test:
a = 1
b = 2
@classmethod
def get(cls, var):
return eval('cls.%s' % var)
a = Test.get('a')
print(a) # output: 1
Upvotes: 0