Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从类实例获取用户定义的类属性_Python_Python 3.x_Python 3.5 - Fatal编程技术网

Python 从类实例获取用户定义的类属性

Python 从类实例获取用户定义的类属性,python,python-3.x,python-3.5,Python,Python 3.x,Python 3.5,如何从类实例中获取用户定义的类属性?我试过这个: class A: FOO = 'foo' BAR = 'bar' a = A() print(a.__dict__) # {} print(vars(a)) # {} 我使用python 3.5。 有办法得到它们吗? 我知道dir(a)返回一个包含属性名称的列表,但我只需要使用已定义的,并且作为dict name to value。尝试以下方法: In [5]: [x for x in dir(a) if not x.s

如何从类实例中获取用户定义的类属性?我试过这个:

class A:
    FOO = 'foo'
    BAR = 'bar'

a = A()

print(a.__dict__)  # {}
print(vars(a))  # {}
我使用python 3.5。 有办法得到它们吗? 我知道
dir(a)
返回一个包含属性名称的列表,但我只需要使用已定义的,并且作为dict name to value。

尝试以下方法:

In [5]: [x for x in dir(a) if not x.startswith('__')]
Out[5]: ['BAR', 'FOO']

您已经在类名称空间中定义了那些尚未传播到实例中的变量。您可以使用实例的
\uuuuu class\uuuuu
属性访问类对象,然后使用
\uuuuuu dict\uuuuu
方法获取命名空间的内容:

>>> {k: v for k, v in a.__class__.__dict__.items() if not k.startswith('__')}
{'BAR': 'bar', 'FOO': 'foo'}

我忘了提到它还应该返回来自家长的属性