Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.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_Object_Types_Attributes - Fatal编程技术网

Python:如何检查对象的属性是否是方法?

Python:如何检查对象的属性是否是方法?,python,object,types,attributes,Python,Object,Types,Attributes,我想用\uu repr\uu方法定义一个类,该方法的定义方式是,它将只写出所有非方法属性的名称和值。我该怎么做?我已经设法这样写了,但是我意识到这并没有检查属性类型 class Example: def __repr__(self): return "\n".join(["%s: %s" % (x, getattr(self, x)) for x in dir(self) if not x.startswith('__')]) 这里缺少的是对属性类型的检查。尝试内置函数

我想用
\uu repr\uu
方法定义一个类,该方法的定义方式是,它将只写出所有非方法属性的名称和值。我该怎么做?我已经设法这样写了,但是我意识到这并没有检查属性类型

class Example:
    def __repr__(self):
        return "\n".join(["%s: %s" % (x, getattr(self, x)) for x in dir(self) if not x.startswith('__')])

这里缺少的是对属性类型的检查。

尝试内置函数callable:

尝试内置函数可调用:

您可以使用
inspect
执行以下操作:

from inspect import ismethod,getmembers

class Example:
    def __repr__(self):
        return "\n".join("%s: %s" % (k, v) for (k,v) in getmembers(self,lambda x: not ismethod(x)))

    def method(self):
        return 1

a = Example()
a.foo = 'bar'
print a

这也会拾取双下划线属性(
\uuuuuu模块\uuuuuu
\uuuuuu文档\uuuuu
)。如果您不想要这些,您可以很容易地将它们过滤掉。

您可以使用
检查
进行如下操作:

from inspect import ismethod,getmembers

class Example:
    def __repr__(self):
        return "\n".join("%s: %s" % (k, v) for (k,v) in getmembers(self,lambda x: not ismethod(x)))

    def method(self):
        return 1

a = Example()
a.foo = 'bar'
print a

这也会拾取双下划线属性(
\uuuuuu模块\uuuuuu
\uuuuuu文档\uuuuu
)。如果你不想要这些,你可以很容易地过滤掉它们。

假设你的类没有定义
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

这张照片

x: [x: [2]
y: [<function <lambda> at 0x7f9368b21ef0>]
z: [4]
w: [1234]]
y: [6j]
z: [b'90']
w: [1234]
x:[x:[2]
y:[]
z:[4]
w:[1234]]
y:[6j]
z:[b'90']
w:[1234]

假设您的类没有定义
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
,您也可以迭代实例的
\uuuuuuuuuuuuuuuuuuuuuuuu

这张照片

x: [x: [2]
y: [<function <lambda> at 0x7f9368b21ef0>]
z: [4]
w: [1234]]
y: [6j]
z: [b'90']
w: [1234]
x:[x:[2]
y:[]
z:[4]
w:[1234]]
y:[6j]
z:[b'90']
w:[1234]

这样做的缺点是可以将可调用对象作为属性:
e=Example();e、 例如,foo=lambda x:x*x
最好是to。这样做的缺点是可以将可调用对象作为属性:
e=example();e、 例如,foo=lambda x:x*x
。最好是to。它还将拾取
@property
和类变量。我认为它应该同时拾取这两种情况。当然是属性对象。毕竟,从API的角度来看,属性和属性之间没有区别。。。但我想这真的取决于OP想要什么:)。它还将拾取
@属性和类变量。我认为它应该同时拾取这两种情况。当然是属性对象。毕竟,从API的角度来看,属性和属性之间没有区别。。。但我认为这确实取决于OP想要什么:)。您可以使用inspect.ismethod查找属性是否为方法类型:)您可以使用inspect.ismethod查找属性是否为方法类型:)