简体   繁体   中英

python 2.7 defining a class that will show their attributes if called with no arguments

I have a class like this:

class DATA:
    # class for the data
    def __init__(self, filename):
        f_in = open(input_file, 'r')
        data = json.load(f_in)
        f_in.close()
        # organizational data
        self.T = data['temperature']
        self.appVersion = data['appVersion']

I can create an object of the class with:

D = DATA(filename)

I can access the attributes with

D.T

The class will have a lot of attributes, and I will soon forget their names... What I need is to have aa prompt with some helpful information if I call D alone.

For example:

>>>D
The attributes of D are:
- T (X)
- appVersion (Y)

where X and Y are the corresponding values.

Is there a build in way to make this happen? Or any other (better) approach?

Thanks.

You can document the attributes in the docstring:

class DATA(object):
    """this says something about the object.

    Attributes:
      T: ...
    """
    ...

Now you can access the documentation that you wrote by:

help(DATA)

or:

print(DATA.__doc__)

If you want that precise functionality, what you get when you type

>>> D

is the return value of DATA.__repr__(D) :

class D(object):
    def __init__(self, ...):
        ...
    def __repr__(self):
         s = "The attributes of D are:\n- T ({0.T})\n- appVersion ('{0.appVersion}')"
         return s.format(self)

Example usage (with overridden __init__ to take data directly):

>>> D = DATA({'temperature': 102, 'appVersion': '1.0.4'})
>>> D
The attributes of D are:
- T (102)
- appVersion ('1.0.4')

However, you should note that this is an abuse of what __repr__ is for; from the documentation :

If at all possible, [ __repr__ ] should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned.

The other answers are, thus, more Pythonic.

You could use the __dict__ attribute:

class Data:
    def __init__(self):
        self.foo = 'value 1'
        self.bar = 'value 2'

d = Data()
print(d.__dict__)

That prints:

{'bar': 'value 2', 'foo': 'value 1'}

To access it on the prompt easily, try this:

def info(obj):
    print(obj.__dict__)

Then at the prompt, just type:

info(d)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM