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

Python's class system

A class can be thought of as a way of assigning a name to a set of specific functions and variables that are all associated with a common piece of an application.

The code for a class differs in two main ways from regular Python code.

Firstly, you will see the class keyword before the name of the class, followed by a colon and an indented scope. This is the syntax for telling Python that everything within this scope belongs to the class.

Secondly, all functions defined will have self as their first argument (unless they are static or class methods). This is automatically passed in via Python itself and so will cause calls to the function to appear to need one fewer argument than the definition.

The purpose of the self argument is to give each function (which, when in the scope of a class, is known as a method instead) access to the instance's other attributes and methods.

Certain types of variables called attributes are available when using classes. Attributes function as regular variables do, but their scope extends to the class instance itself. This means these variables can be shared among all functions defined within the class without the need to use the global keyword.

Attributes are differentiated from regular variables by the use of self. in front of them. For example, the line age = 20 creates a variable called age, whereas self.age = 20 creates an attribute against the class instance.

Once you have determined which attributes and methods to bundle together into a class, you can then create instances of it.

主站蜘蛛池模板: 岳普湖县| 贺兰县| 安陆市| 桃园市| 灵武市| 峡江县| 玉田县| 盈江县| 石城县| 康定县| 莱芜市| 札达县| 杭州市| 弥勒县| 榆林市| 康乐县| 即墨市| 宾阳县| 昭平县| 灵川县| 茌平县| 塔河县| 金塔县| 连山| 朝阳县| 长春市| 灵山县| 大厂| 张家口市| 婺源县| 濮阳县| 天长市| 肇州县| 东乌珠穆沁旗| 卢氏县| 柳林县| 察哈| 勐海县| 揭东县| 江口县| 临桂县|