Objects have functions, which we call *methods* to distinguish them from functions not associated with objects. Objects also have variables, which we call *fields* or *instance variables*.
A class is a blueprint for multiple objects, often called *instances*. The class *encapsulates* the state and behavior of an object.
Imagine an alien lands in your backyard and asks you to describe a car. You would probably describe its attributes, such as the number of wheels, and its functionality, such as can start and stop. These are the state and behavior. By defining them, we effectively define the object. The class name is just giving a name to the entity.
By convention, class names should be capitalized like `Point`.
## Tuples as object substitutes
The fields of an object are the data items we want to associate together. For example, if I want to track book titles/authors, I can use a list of tuples:
对象的字段是我们想要关联在一起的数据项。 例如,如果我想跟踪书名/作者,我可以使用元组列表:
```python
fromlolvizimport*
...
...
@@ -162,14 +153,8 @@ books = [
objviz(books)
```
![svg](img/2.8_OO_26_0.svg)
```python
forbinbooks:
print(f"{b[1]}: {b[0]}")
...
...
@@ -180,7 +165,6 @@ David Brin: Startide Rising
'''
```
```python
# Or, more fancy
fortitle,authorinbooks:
...
...
@@ -192,12 +176,11 @@ David Brin: Startide Rising
'''
```
To access the elements of the tuple in both cases, we have to keep track of the order in our heads. In other words, we have to access the tuple elements like they are list elements, which they are.
A better way is to formally declare that author and title data elements should be encapsulated into a single entity called a book. Python has what I consider an extremely quirky specification but it is extremely flexible. For example, we can define an object that has no methods and no fields but then can add fields dynamically with assignment statements:
But this doesn't let us define methods associated with that object (easily). Let's take a look at our first real class definition that contains a function called a *constructor*.
Notice that we do not pass the `self` parameter to the constructor. **It's implicit at the call site but explicit at the definition site!**
请注意,我们不会将`self`参数传递给构造函数。 **它在调用一侧隐藏,但在定义一侧出现!**
## Naughty behavior
Also notice that we have been setting fields of objects using the constructor, by Python in its infinite flexibility allows you to do very **naughty** things such as setting fields on arbitrary objects: