关于python:获取类的属性

Getting attributes of a class

我想得到一个类的属性,比如:

1
2
3
4
5
6
class MyClass():
  a ="12"
  b ="34"

  def myfunc(self):
    return self.a

使用MyClass.__dict__给了我一个属性和函数的列表,甚至像__module____doc__这样的函数。而MyClass().__dict__给了我一个空的dict,除非我显式地设置了该实例的属性值。

我只需要属性,在上面的示例中,这些属性是:ab


(P)Try the Inspect Module.EDOCX1和各种测试应该有帮助。(p)(P)Edit:(p)(P)For example,(p)字母名称(P)Now,the special methods and attributes get on my nerves-those can be dealt with in a number of ways,the easiest of which is just to filter based on name.(p)字母名称(P)……and the more complicated of which can include special attribute name checks or even metaclasses;*(p)


字母名称


(P)EDOCX1是一个字母表3。That's how it's found when you run:(p)字母名称(P)It looks for an attribute on EDOCX1 plography 4 named EDOCX1 plus 2,doesn't find one,sees that EDOCX1 plographic 4 is an instance of EDOCX1 penal 3 and looks it up there.(p)(P)So the complete list of attributes for EDOCX1 university 3 is:(p)字母名称(P)(note that I'm using dir just as a quick and easy way to list the members of the class:it should only be used in an exploratory fashion,not in production code)(p)(P)如果你只是想特别表达意见,那么你就需要用一些标准来确定这份名单,因为你是用英文字母9,字母名称10,字母名称10,字母名称EDOCX1,字母名称2,字母名称2,字母名称2,Aren't special in any way,they're attributes in exactly the same way that EDOCX1(p)(P)I've never used the inspect module referred to by matt and borelid,but from a brief link i t looks like i t has tests to help you do this,but you'll need to write your own predicate function,since i t seems what you want is roughly the attributes that don't pass the EDOCX1 y 14.Test and don't start and end with two underscores.(p)(P)Also note:by using EDOCX1 in Python 2.7 you're using the wildly out of date-style classes.由于你在这么大的辩论中与极其老的图书馆保持一致,你应该敦促界定你的分类为英文名称16。在Python 3,there are no"old-style"classes,and this behaviour is the default.然而,使用新闻分类将使你更自动地表达自己的观点:(p)字母名称


(P)字母名称(p)(P)然而,"权利"是通过检查模块来实现的。(p)


只获取实例属性很容易。但是,在没有函数的情况下获取类属性会更复杂一些。

仅实例属性

如果只需要列出实例属性,只需使用for attribute, value in my_instance__dict__items()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> from __future__ import (absolute_import, division, print_function)
>>> class MyClass(object):
...   def __init__(self):
...     self.a = 2
...     self.b = 3
...   def print_instance_attributes(self):
...     for attribute, value in self.__dict__.items():
...       print(attribute, '=', value)
...
>>> my_instance = MyClass()
>>> my_instance.print_instance_attributes()
a = 2
b = 3
>>> for attribute, value in my_instance.__dict__.items():
...   print(attribute, '=', value)
...
a = 2
b = 3

实例和类属性

为了获得没有函数的类属性,技巧是使用callable()

但是静态方法并不总是callable

因此,不使用callable(value)用途callable(getattr(MyClass, attribute)))

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from __future__ import (absolute_import, division, print_function)

class MyClass(object):
   a ="12"
   b ="34"               # class attributes

   def __init__(self, c, d):
     self.c = c
     self.d = d           # instance attributes

   @staticmethod
   def mystatic():        # static method
       return MyClass.b

   def myfunc(self):      # non-static method
     return self.a

   def print_instance_attributes(self):
     print('[instance attributes]')
     for attribute, value in self.__dict__.items():
        print(attribute, '=', value)

   def print_class_attributes(self):
     print('[class attributes]')
     for attribute in MyClass.__dict__.keys():
       if attribute[:2] != '__':
         value = getattr(MyClass, attribute)
         if not callable(value):
           print(attribute, '=', value)

v = MyClass(4,2)
v.print_class_attributes()
v.print_instance_attributes()

注:print_class_attributes()@staticmethod。  但在这个愚蠢而简单的例子中不是这样。

Python2结果

1
2
3
4
5
6
7
$ python2 ./print_attributes.py
[class attributes]
a = 12
b = 34
[instance attributes]
c = 4
d = 2

对python3的结果相同

1
2
3
4
5
6
7
$ python3 ./print_attributes.py
[class attributes]
b = 34
a = 12
[instance attributes]
c = 4
d = 2


我不知道现在是否已经做了类似的事情,但是我用vars()做了一个很好的属性搜索函数。vars()创建一个您通过它传递的类的属性字典。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Player():
    def __init__(self):
        self.name = 'Bob'
        self.age = 36
        self.gender = 'Male'

s = vars(Player())
#From this point if you want to print all the attributes, just do print(s)

#If the class has a lot of attributes and you want to be able to pick 1 to see
#run this function
def play():
    ask = input("What Attribute?>:")
    for key, value in s.items():
        if key == ask:
            print("self.{} = {}".format(key, value))
            break
    else:
        print("Couldn't find an attribute for self.{}".format(ask))

我在Python中开发了一个相当大的文本冒险,到目前为止我的播放器类有100多个属性。我使用这个搜索我需要看到的特定属性。


字母名称(P)For an instance of Myclass,such as(p)字母名称(P)在《清单》中使用EDOCX1标语32的字母表However,if one dynamically adds an attribute to EDOCX1 penographic 34,such as EDOCX1 penographic 35,the attribute won't show up when using EDOCX1 penographical 32 in this strategy.It only gives the attributes of the original class.(p)(P)为了获得全书的一个阶级瞬间,你需要将EDOCX1的英文字典37和EDOCX1的英文字母表38结合起来。(p)字母名称


(P)My solution to get all attributes(not methods)of a class(if the class has a properly written docstring that has the attributes clearly spelled out):(p)字母名称(P)这个Piece EDOCX1拼写17个音符《班级教学》(p)


我想这可以不用检查就能做到。

学习以下课程:

1
2
3
4
5
6
7
8
9
10
11
12
13
 class Test:
   a = 1
   b = 2

   def __init__(self):
     self.c = 42

   @staticmethod
   def toto():
     return"toto"

   def test(self):
     return"test"

查看成员及其类型:

1
2
t = Test()
l = [ (x, eval('type(x.%s).__name__' % x)) for x in dir(a) ]

…给予:

1
2
3
4
5
6
7
8
[('__doc__', 'NoneType'),
 ('__init__', 'instancemethod'),
 ('__module__', 'str'),
 ('a', 'int'),
 ('b', 'int'),
 ('c', 'int'),
 ('test', 'instancemethod'),
 ('toto', 'function')]

因此,要只输出变量,只需按类型筛选结果,而不必以"uuuu"开头。例如。

1
2
3
filter(lambda x: x[1] not in ['instancemethod', 'function'] and not x[0].startswith('__'), l)

[('a', 'int'), ('b', 'int'), ('c', 'int')] # actual result

就这样。

注意:如果您使用的是Python3,请将迭代器转换为列表。

如果您想要一种更健壮的方法来完成它,请使用inspect。


您可以在列表理解中使用dir()来获取属性名:

1
names = [p for p in dir(myobj) if not p.startswith('_')]

使用getattr()获取属性本身:

1
attrs = [getattr(myobj, p) for p in dir(myobj) if not p.startswith('_')]


(P)I recently need to figure out some similar to this question,so I wanted to post some background info that might be helpful to others facing the same in future.(p)(P)Here's how it works in python(from https://docs.python.org/3.5/reference/datalmodel.html§35;The-Standard-Type-Hierarchy):(p)(P)EDOCX1是一种阶级目标,EDOCX1是一种语言19,是一种阶级目标的瞬间。An instance's EDOCX1 penographical 20 universal only hold attributes and methods specific to that instance(E.G.EDOCX1 universal 21).如果一种观念或方法是一个类别的一部分,它是在英文的"EDOCX1"类别中。When you do EDOCX1 pental 23 silian,an instance of EDOCX1 pental 3 is created with no attributes or methods besides the class attributes,thus the empty EDOCX1(p)(P)So if you say EDOCX1 penographic 26,Python first checks the new instance's dict EDOCX1 penographic 27 and fails to find EDOCX1 penographic 13.他们检查了"EDOCX1"的音标29和"EDOCX1"的音标13。(p)(P)那你为什么要用"EDOCX1"来模拟同样的搜索过程(p)


您可以使用MyClass.__attrs__。它只提供该类的所有属性。没别的了。


两种功能:

1
2
3
4
5
6
7
8
9
10
11
12
def get_class_attr(Cls) -> []:
    import re
    return [a for a, v in Cls.__dict__.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

def get_class_attr_val(cls):
    attr = get_class_attr(type(cls))
    attr_dict = {}
    for a in attr:
        attr_dict[a] = getattr(cls, a)
    return attr_dict

用途:

1
2
3
4
5
6
7
8
9
>>> class MyClass:
    a ="12"
    b ="34"
    def myfunc(self):
        return self.a

>>> m = MyClass()
>>> get_class_attr_val(m)
{'a': '12', 'b': '34'}


有一个非常简单的答案,应该是显而易见的:getattr

1
2
3
4
5
6
7
8
9
10
11
class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
    return self.a

>>> getattr(MyClass, 'a')
'12'

>>> getattr(MyClass, 'myfunc')
<function MyClass.myfunc at 0x10de45378>

它在python 2.7和python 3.x中都很出色。

如果您想要这些项目的列表,您仍然需要使用inspect。


(P)I know this was three years ago,but for those who are to come by this question in the future,for me:(p)字母名称(P)Works just fine.(p)