point.md 2.1 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
# Python 类创建

创建点对象,有多种方式创建一个类的实例,我们称一个点的x、y、z都一样的点为对角点。

```python
# -*- coding: UTF-8 -*-
class Point:
    # TODO(You): 添加代码支持类的创建

if __name__ == '__main__':
    points = []

    # TODO(You): 批量创建1000个对角点,第i个点的坐标是 (i,i,i)

    for point in points:
        print(point)
```

以下对上述代码补全,不正确的是?

## template

```python
class Point:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

if __name__ == '__main__':
    points = []
    for i in range(1000):
        points.append(Point(i,i,i))

    for point in points:
        print(point)
```

## 答案

```python
class Point:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

if __name__ == '__main__':
    points = []
    for i in range(1000):
        points.append(new Point(i,i,i))
```

## 选项

### A

```python
class Point:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

if __name__ == '__main__':
    points = []
    for i in range(1000):
        points.append(Point(i,i,i))
```

### B

```python
# 通过 @classmethod 装饰器,增加一个类级别的创建方法,批量创建
class Point:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    @classmethod
    def create_diag_points(cls, count):
        # 在@classmethod修饰的方法中,其中 cls 表示 Point
        points = []
        for i in range(count):
            points.append(cls(i,i,i))
        return points

if __name__ == '__main__':
    points = Point.create_diag_points(1000)
```

### C

```python
# 添加类静态方法,批量创建对角点
class Point:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    @staticmethod
    def create_diag_points(count):
        points = []
        for i in range(count):
            points.append(Point(i,i,i))
        return points

if __name__ == '__main__':
    points = Point.create_diag_points(1000)
```