简体   繁体   中英

make a list of class attributes in the order they appear

I have a tuple of classes in the following format:

In: print(my_tuple)

Out: (class_name(c=1, b=2, a=3),class_name(c=4, b=5, a=6),class_name(c=7, b=8, a=9))

How can I make a list of the tuple 's classes atributes, in the same order that those attributes appear?

The result should be:

In: print(my_list)

Out: [c, b, a]

I've got this code, but the resulting list comes sorted in alphabetical order: (All classes attributes are standardized, so I can use the first class as a model)

attributes = inspect.getmembers(class_name[0], lambda a:not(inspect.isroutine(a)))
my_list = [a[0] for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]

You can use inspect.getfullargspec :

In [41]: class Test:
    ...:     def __init__(self, c=1, b=2, a=3):
    ...:         pass
    ...:

In [42]: inspect.getfullargspec(Test)
Out[42]: FullArgSpec(args=['self', 'c', 'b', 'a'], varargs=None, varkw=None, defaults=(1, 2, 3), kwonlyargs=[], kwonlydefaults=None, annotations={})

In [43]: inspect.getfullargspec(Test).args
Out[43]: ['self', 'c', 'b', 'a']

EDIT:

If you're dealing with an instance of a class, you can call it on the type instead of the instance itself like so:

In [62]: t=Test()

In [63]: inspect.getfullargspec(t)  # Throws TypeError

In [64]: inspect.getfullargspec(type(t))  # Call on type
Out[64]: FullArgSpec(args=['self', 'c', 'b', 'a'], varargs=None, varkw=None, defaults=(1, 2, 3, 4), kwonlyargs=[], kwonlydefaults=None, annotations={})

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