gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:52:43 26 4
gpt4 key购买 nike

目标(在 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)

目标是为我没有源代码(或不想修改源代码)的类提取类似的信息。那些类有很多类变量,隐藏了我寻找的信息。

问题:

如何检测“零”是从 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 上的“零”,它就会被包含在内:

# 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)

最佳答案

这样的事情可能会奏效

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

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

关于Python:如何确定属性(按名称)是类属性还是实例属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20201029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com