# Python 获取对象信息 过滤列表里所有含有 'z' 属性的对象,打印他们的 'x'+'y'+'z' 的值 ```python # -*- coding: UTF-8 -*- class Point2D: def __init__(self, x, y) -> None: self.x = x self.y = y class Point3D: def __init__(self, x, y, z) -> None: self.x = x self.y = y self.z = z class Vector2D: def __init__(self, x, y) -> None: self.x = x self.y = y class Vector3D: def __init__(self, x, y, z) -> None: self.x = x self.y = y self.z = z def test(): points = [ Point2D(0, 1), Point2D(0, 1), Point3D(0, 1, 2), Point3D(0, 1, 3), Vector2D(0, 1), Vector3D(0, 1, 4), ] z_objects = [] # TODO(You): 请在此过滤出含有'z'属性的对象,在过滤中打印出对应对象的'z'属性 for p in z_objects: print('x+y+z:', p.x+p.y+p.z) if __name__ == '__main__': test() ``` 请选出下列能**正确**实现这一功能的选项。 ## template ```python class Point2D: def __init__(self, x, y) -> None: self.x = x self.y = y class Point3D: def __init__(self, x, y, z) -> None: self.x = x self.y = y self.z = z class Vector2D: def __init__(self, x, y) -> None: self.x = x self.y = y class Vector3D: def __init__(self, x, y, z) -> None: self.x = x self.y = y self.z = z def test(): points = [ Point2D(0, 1), Point2D(0, 1), Point3D(0, 1, 2), Point3D(0, 1, 3), Vector2D(0, 1), Vector3D(0, 1, 4), ] z_objects = [] for p in points: if hasattr(p, 'z'): z = getattr(p, 'z') print('get z attr:', z) z_objects.append(p) for p in z_objects: print('x+y+z:', p.x+p.y+p.z) if __name__ == '__main__': test() ``` ## 答案 ```python for p in points: if hasattr(p, 'z'): z = getattr(p, 'z') print('get z attr:', z) z_objects.append(p) ``` ## 选项 ### A ```python for p in points: z = getattr(p, 'z') print('get z attr:', z) z_objects.append(p) ``` ### B ```python for p in points: if not hasattr(p, 'z'): z = getattr(p, 'z') print('get z attr:', z) z_objects.append(p) ``` ### C ```python for p in points: if p.hasattr('z'): z = p.getattr(p, 'z') print('get z attr:', z) z_objects.append(p) ```