- Python 3 Object Oriented Programming
- Dusty Phillips
- 205字
- 2021-08-03 15:36:07
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!
- Microsoft Visual C++ Windows Applications by Example
- 商用級AIGC繪畫創作與技巧(Midjourney+Stable Diffusion)
- Photoshop 2022從入門到精通
- CoffeeScript Application Development
- Zenoss Core Network and System Monitoring
- 視覺封王:Photoshop CC 2019立體化教程(素材+視頻+教案)
- AI圖像處理:Photoshop+Firefly后期處理技術基礎與實戰
- CAD/CAM技術與應用
- 24小時全速學會Photoshop 2021
- IT Inventory and Resource Management with OCS Inventory NG 1.02
- 好用,Excel數據處理高手
- 中文版Photoshop CS6完全自學手冊(超值版)
- AutoCAD 2019中文版實戰從入門到精通
- Altium Designer 20 中文版從入門到精通
- 從零開始:Dreamweaver CS6中文版基礎培訓教程