官术网_书友最值得收藏!

Adding attributes

Now, we have a basic class, but it's fairly useless. It doesn't contain any data, and it doesn't do anything. What do we have to do to assign an attribute to a given object?

It turns out that we don't have to do anything special in the class definition. We can set arbitrary attributes on an instantiated object using the dot notation:

class Point:
    pass

p1 = Point()
p2 = Point()

p1.x = 5
p1.y = 4

p2.x = 3
p2.y = 6

print(p1.x, p1.y)
print(p2.x, p2.y)

If we run this code, the two print statements at the end tell us the new attribute values on the two objects:

5 4
3 6

This code creates an empty Point class with no data or behaviors. Then it creates two instances of that class and assigns each of those instances x and y coordinates to identify a point in two dimensions. All we need to do to assign a value to an attribute on an object is use the syntax <object>.<attribute> = <value>. This is sometimes referred to as dot notation. The value can be anything: a Python primitive, a built-in data type, another object. It can even be a function or another class!

主站蜘蛛池模板: 沽源县| 保德县| 兖州市| 小金县| 乌拉特前旗| 石阡县| 铜山县| 五河县| 嘉禾县| 和田市| 临漳县| 东乡县| 阜阳市| 武定县| 大理市| 思南县| 德兴市| 怀仁县| 安康市| 梅州市| 万宁市| 邳州市| 大关县| 湖口县| 江西省| 鞍山市| 九寨沟县| 杨浦区| 九龙坡区| 普兰店市| 奇台县| 高唐县| 七台河市| 富源县| 友谊县| 岚皋县| 福海县| 合阳县| 石景山区| 三门峡市| 香港|