Marmstrong
Marmstrong

Reputation: 1786

How to view the instance variables of a class

I have a list of settings defaults held within my init function. These defaults are all instance variables. For example,

self.set_acqmode = 1
self.set_readmode = 4
self.set_triggermode = 0

I have a function within this class which I want to use to change these default settings by only passing in a name and a value as arguments. For example,

def change_setting(self, setting, *arg):

What would be a pythonic way of accessing and changing the correct instance variable. I have tried using both vars() and dict to view these variables but the former only showed the the classes functions and the latter needs to refer to a instance of the class (which won't exist yet as this is within the class).

(If there is a better way of doing this without searching for the variables I would still like to know how to view them, just out of interest.)

Upvotes: 1

Views: 183

Answers (4)

Corley Brigman
Corley Brigman

Reputation: 12381

setattr will work. But you have to ask, if you're going through all this trouble to rewrite setattr, are you even doing this the right way?

If you just want to have some arbitrary keys & values - well, that's a dictionary, and you should use it as such. override __getitem__/__setitem__ if you need custom behaviour.

if you really need attributes, then there's no reason a parent function wouldn't just do

myobj.set_triggermode = value

rather than the overly complex

myobj.change_setting('triggermode', value)

so you should do that. and even if you want to do that for some reason - use kwargs instead of args, probably closer to what you want.

Upvotes: 1

dg99
dg99

Reputation: 5663

You can use __dict__ on the name of a class without having instantiated an object of that class. For example:

print myClass.__dict__.keys()

::edit:: Of course, if you're being rigorous in your programming, you may consider using __slots__, in which case you will have predefined all the instance variables of your class by yourself.

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 121986

You can certainly use __dict__:

>>> class Test(object):
    def __init__(self):
        self.x = 1
    def set(self, attr, val):
        self.__dict__[attr] = val

>>> a = Test()
>>> a.set('x', 2)
>>> a.x
2

Upvotes: 1

ndpu
ndpu

Reputation: 22561

Use setattr:

def change_setting(self, setting, *arg):
    setattr(self, setting, arg)

Upvotes: 4

Related Questions