如何从类实例内部获取所有int?

时间:2018-06-28 21:38:04

标签: python types python-2.x

我想从一个未知的类实例中获取所有int类型。

如果我有以下课程:

class myclass:
    g_goodies = 0
    g_stringer = "bob"
    mylist = []

    def __init__(self,goodies):
        self.g_goodies = goodies
        for x in range(0,10):
            self.mylist.append(0)

我已经尝试过...

def get_ints(self,inobject):
    a = inspect.getmembers(inobject)
    b = len(a)
    print 'a:',a,' b:',b
    print 'a type:',type(a),' b type:',type(b)
    for x in range(0,b-1):
        c = type(a[x])
        print c

print "Hello World!\n"
mc = myclass(10)
pa = printanything()
print pa.get_ints(mc)

哪个给我:

$python main.py
Hello World!

a: [('__doc__', None), ('__init__', <bound method myclass.__init__ of <__main__.myclass instance at 0x7f34ee9e80e0>>), ('__module__', '__main__'), ('g_goodies', 10), ('g_stringer', 'bob'), ('mylist', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])]  b: 6
a type: <type 'list'>  b type: <type 'int'>
<type 'tuple'>
<type 'tuple'>
<type 'tuple'>
<type 'tuple'>
<type 'tuple'>
None

所以我只希望能够提取类实例中的所有类型int,类对象中的所有类型str,等等……在运行时该类未知

1 个答案:

答案 0 :(得分:0)

您遗漏了很多问题,但这是一个猜测,显示了如何做与我想做的事情类似的事情:

from __future__ import print_function
import inspect
from pprint import pprint, pformat


class MyClass:
    g_goodies = 0
    g_stringer = "bob"
    mylist = []

    def __init__(self,goodies):
        self.g_goodies = goodies
        for _ in range(10):
            self.mylist.append(0)


def get_ints(inobject):
    return [name for (name, value) in inspect.getmembers(inobject)
                if isinstance(value, int)]

mc = MyClass(10)
print(get_ints(mc))  # -> ['g_goodies']

请注意,未显示mylist,因为它是list而不是int,但是您可以可以修改get_ints()来检查内容如果您愿意,它也可以遇到list的任何>。