java class getfields_与Java的getClass().getFields()等价的Python

首先,我要强调的是,Python中没有getClass().getFields(),因为一个对象可以有很多未由类定义的字段。实际上,要在Python中创建一个字段,只需为其指定一个值。这些字段不是定义的,而是创建的:>>> class Foo(object):

... def __init__(self, value):

... # The __init__ method will create a field

... self.value = value

...

>>> foo = Foo(42)

>>> foo.value

42

>>> # Accessing inexistent field

... foo.another_value

Traceback (most recent call last):

File "", line 2, in

AttributeError: 'Foo' object has no attribute 'another_value'

>>> # Creating the field

... foo.another_value = 34

>>> # Now I can use it

... foo.another_value

34

所以,你不能从类中得到字段。相反,你可以从一个对象中获取字段。在

另外,Python方法只是具有一些特殊值的字段。方法只是函数的实例:

^{pr2}$

需要注意的是,要清楚地表明Python中没有getClass().getMethods()这样的方法,getClass().getFields()的“等价物”也将返回方法。在

也就是说,如何获得字段(或属性,因为它们在Python中经常被调用)?当然,不能从类中获取它们,因为对象存储它们。因此,您可以使用dir()函数获得对象属性的名称:>>> dir(foo)

['__class__', '__delattr__', '__dict__', '__doc__', '__format__',

'__getattribute__', '__hash__', '__init__', '__module__', '__new__',

'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',

'__str__', '__subclasshook__', '__weakref__', 'another_value', 'value']

获得属性名后,可以使用getattr()函数获取每个属性名:>>> getattr(foo, 'value')

42>>> [getattr(foo, attrname) for attrname in dir(foo)]

[, ,

{'another_value': 34, 'value': 42}, None, ,

,

... # Lots of stuff

34, 42]

最后,您可以找到在某些属性上设置的值。在

但是,这个列表也将包含方法。记住它们也是属性。在这种情况下,我们可以使列表理解避免调用属性:>>> [attrname for attrname in dir(foo) if not callable(getattr(foo, attrname))]

['__dict__', '__doc__', '__module__', '__weakref__', 'another_value', 'value']

现在,得到实际值:>>> [getattr(foo, attrname) for attrname in dir(foo)

... if not callable(getattr(foo, attrname))]

[{'another_value': 34, 'value': 42}, None, '__main__', None, 34, 42]

还有一些奇怪的值,比如__dict__,__doc__等等,它们是一些你可能想忽略的东西。如果是这样的话,在你的列表理解中再加上一个标准:>>> [attrname for attrname in dir(foo)

... if not attrname.startswith('__') and

... not callable(getattr(foo, attrname))]

['another_value', 'value']

>>> [getattr(foo, attrname) for attrname in dir(foo)

... if not attrname.startswith('__') and

... not callable(getattr(foo, attrname))]

[34, 42]

还有其他方法可以做这些事情。例如,可以查看对象的__dict__和__slots__属性。然而,我发现我提出的方法对初学者来说更清晰。在

编辑另外两个点。{{a3}建议你先看一看。在

另外,您可能需要同时获得属性的名称和值。您可以让它生成元组列表:>>> [(attrname, getattr(foo, attrname)) for attrname in dir(foo)

... if not attrname.startswith('__') and

... not callable(getattr(foo, attrname))]

[('another_value', 34), ('value', 42)]>>> import inspect

>>> inspect.getmembers(foo)

[('__class__', ),

# ... Lots of stuff ...

('another_value', 34), ('value', 42)]

要删除方法,只需避免调用:>>> inspect.getmembers(foo, lambda attr: not callable(attr))

[('__dict__', {'another_value': 34, 'value': 42}), ('__doc__', None), ('__module__', '__main__'), ('__weakref__', None), ('another_value', 34), ('value', 42)]

(不幸的是,inspect.ismethod()没有像我预期的那样工作。)

还有很多内部的东西,我们不能像使用方法那样直接输出。列表理解无法再解决的问题:>>> [(name, value) for name, value in inspect.getmembers(foo, lambda attr: not callable(attr))

... if not name.startswith('__')]

[('another_value', 34), ('value', 42)]

Python是一种非常动态的语言,这种解决方案在某些情况下不能很好地工作。考虑到有可能有一个对象,它应该存储一个函数,以便在某处使用。函数是一个可调用的对象,属性将不显示。然而,它在逻辑上是一个属性,一个要使用的数据。你应该记住这种事。不过,我打赌你不会经常遇到这样的问题。在

高温

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值