Python:如何确定属性(按名称)是类还是实例属性?

时间:2013-11-25 18:59:43

标签: python class attributes inspect

目标(在Python 2.7中):

检查任意对象,找到所有实例变量。但是排除类变量。

终极目标:

从不提供有用“str”实现的第三方类库中打印对象的有用详细信息。 (Maya的Python API,版本1,这是一个简单的SWIG包装器。 不使用版本2,因为我正在学习一些版本1的例子。)

示例类:

# ---------- class Vector ----------
class Vector(object):
    def __init__(self, x=0.0, y=0.0, z=0.0):
        self.x, self.y, self.z = x, y, z
    # Provide useful info for 'repr(self)', 'str(self)', and 'print self'.
    def __repr__(self):
        return 'Vector({0}, {1}, {2})'.format(self.x, self.y, self.z)
    # math operators
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
    # a simple method
    def ApproximateLength(self):
        return self.x + self.y + self.z
    # list/sequence/iterator support.
    def tolist(self):
        return [self.x, self.y, self.z]
    def __len__(self):
        return 3
        # No need for "next(self)", because we create a list, use its iterator.
    def __iter__(self):
        return iter(self.tolist())
# class variable
Vector.Zero = Vector()

到目前为止的解决方案:

import inspect
import types
def printElements(ob):
    for x in ob: print x
# Excludes 'internal' names (start with '__').
def Public(name):
    return not name.startswith('__')
def Attributes(ob):
    # Exclude methods.
    attributes = inspect.getmembers(ob, lambda member: not inspect.ismethod(member))
    # Exclude 'internal' names.
    publicAttributes = filter(lambda desc: Public(desc[0]), attributes)
    return publicAttributes

使用示例:

vec = Vector(1.0, 2.0, 3.0)
printElements(Attributes(vec))   

输出:

('Zero', Vector(0.0, 0.0, 0.0))
('x', 1.0)
('y', 2.0)
('z', 3.0)

这门课打印得很好:

print vec

=>

Vector(1.0, 2.0, 3.0)

目标是为我没有源的类(或者不想修改源)提取类似的信息。这些类有很多类变量,它们会掩盖我所寻求的信息。

问题:

如何检测'Zero'是继承自Vector的“类变量”,以便从输出中消除它?

如果没有更好的方法,我将使用笨拙的方法:

printElements(Attributes(type(vec)))

列出对象类型的属性。可以针对“type(vec)”的属性测试“vec”的每个属性,排除任何匹配。我并不关心在类和实例上存在相同命名属性的微妙可能性。所以这将满足我的要求。

然而,这看起来很笨拙。是否有更直接的方法来确定属性是否从类继承?


编辑:纳入Joran的回答

def IsClassVar(self, attrName):
    return hasattr(self.__class__, attrName)
def Attributes(ob):
    ....
    publicAttributes = filter(lambda desc: Public(desc[0]), attributes)
    # Exclude 'class' variables.
    # NOTE: This does not attempt to detect whether the instance variable is different than the class variable.
    publicAttributes = filter(lambda desc: not isClassVar(ob, desc[0]), publicAttributes)
    return publicAttributes

这给出了期望的结果:

printElements(Attributes(vec))   

=>

('x', 1.0)
('y', 2.0)
('z', 3.0)

替代方法,检测实例变量覆盖类变量:

def IsClassVar(self, attrName):
    return hasattr(self.__class__, attrName)
# REQUIRE attrName already known to be supported by self.
# But just in case, return False if exception, so will be skipped.
def IsNotSameAsClassVar(self, attrName):
    try:
        if not IsClassVar(self, attrName):
            return True
        # If it has different value than class' attribute, it is on the instance.
        return getattr(self, attrName) is not getattr(self.__class__, attrName)
    except:
        return False
def Attributes(ob):
    ....
    publicAttributes = filter(lambda desc: Public(desc[0]), attributes)
    # Exclude 'class' variables.
    # More complete solution.
    publicAttributes = filter(lambda desc: IsNotSameAsClassVar(ob, desc[0]), publicAttributes)
    return publicAttributes

现在,如果我们覆盖vec上的'Zero',它将被包含在内:

# Probably a bad idea, but showing the principle.
vec.Zero = "Surprise!"

然后:

print vec.Zero
print Vector.Zero

=>

Surprise!
Vector(0.0, 0.0, 0.0)

printElements(Attributes(vec))   

=>

('Zero', 'Surprise!')
('x', 1.0)
('y', 2.0)
('z', 3.0)

1 个答案:

答案 0 :(得分:4)

这样的事情可能会起作用

def isClassVar(self,varname):
        return hasattr(self.__class__,varname)
...
vec.isClassVar("Zero")

请注意,这并不一定意味着它是一个实例变量......只是那不是一个类变量