object_meta.md 2.5 KB
Newer Older
F
feilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
# 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)
```