0

I have a class in python and I'd like to get one of several attributes depending on a string like this:

class my_class:
    def __init__(self):
        self.att1=1
        self.att2=2
        self.att3=3

    def getatt (self, number):
        return self.att(number)

How can I make this happen?

0

2 Answers 2

5
def getatt(self, number):
    return getattr(self, 'att%d' % number)

Or with new style formatting:

def getatt(self, number):
    return getattr(self, 'att{}'.format(number))

Also note that if you have many of these attributes, you should perhaps consider storing a list and retrieve elements from their index.

Sign up to request clarification or add additional context in comments.

1 Comment

if there is a meaning to the names and you also want lookup by numbers, also take a look at namedtuple
0

I would do something like

class My_Class:
    def __init__(self):
        self.att = {1: 1, 2: 2, 3: 3}
    def getatt(self, number):
        return self.att[number]
    def __getattr__(self, attname):
        if attname.startswith('att') and attname != 'att':
            try: num = int(attname[3:])
            except ValueError: pass
            else: return self.att[num]
        raise AttributeError(attname)

(untested)

With this, you can access your data bundled and as well as attributes if needed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.