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

Classes

The final fundamental building block we're going to discuss in this section is classes. The word class is a synonym for category or type; in this case, it is referring to data values.

A class defines a new kind of data value by describing a set of internal data and operations for that type of data value. This is done primarily by defining a group of functions that make up the class. A special function called __init__ is used to set up the internal data for a new data value of this type, and the rest of the functions define the operations on an existing data value of this type:

class Frood: 
    def __init__(self, age): 
        self.age = age 
        print("Frood initialized") 
 
    def anniversary(self): 
        self.age += 1 
        print("Frood is now {} years old".format(self.age)) 
 
f1 = Frood(12) 
f2 = Frood(97) 
f1.anniversary() 
f2.anniversary() 
f1.anniversary() 
f2.anniversary() 

All the functions of a class receive a parameter called self, as shown in the preceding code example for classes. This parameter is the data value being operated on. That's different from C++ or Java because while those languages do basically the same thing, the parameter is implicit instead of being an explicit part of the function's parameter list.

Class functions, including __init__, should store and retrieve data from self when they want to manipulate the data value that they're connected to.

Classes support inheritance and multiple inheritance, but we won't go into that in detail at this point in the book.

In the preceding example, we created a new data type called Frood and then made two separate data values of that type. Then, we used the anniversary function that we created as part of the class to modify each of them.

The output of the code example for classes is as follows:

The two instances maintain their internal variables with different values, as shown in the preceding output.
主站蜘蛛池模板: 元朗区| 谢通门县| 齐齐哈尔市| 双辽市| 大同县| 济南市| 车致| 隆子县| 什邡市| 广宗县| 诸暨市| 大理市| 黄浦区| 鄱阳县| 衡阳县| 南澳县| 沾益县| 新化县| 九台市| 五原县| 吴忠市| 枣阳市| 巴彦淖尔市| 磐石市| 万州区| 家居| 孟津县| 潞城市| 阿鲁科尔沁旗| 邓州市| 吉林省| 阿拉尔市| 安国市| 博湖县| 托克托县| 循化| 佳木斯市| 若尔盖县| 临夏市| 新平| 渭南市|