Getting started learning Python: awareness classes and objects

table of Contents

Python class definition:


Python class definition:

Python is a class using the class keyword with which the basic syntax is as follows:

class name of the class:
    a plurality of (≧ 0) ... class attributes
    plurality (≧ 0) ... class methods

 It refers to the class attributes included in the variable class; refers to a class method and comprising a function of the class. In other words, class attributes and class methods are actually contain variables and functions class nickname.

'''这是一个学习定义第一个类'''

class TheFirstDemo:
    # 下面定义了一个类属性
    add = 'ziyuejiaoyu'
    # 下面定义了一个say方法
    def say(self, content):
        print(content

        We have created a class called TheFirstDemo, which contains a class named add the property. Note that, depending on the definition of attributes of positions, each of the variables outside the defined class method called class property or class variables (e.g., add attributes), defined in the class instance attributes called process attributes (or instance variables).

When creating a class, we can manually add a __init __ () method, which is a particular instance of the class method called constructor (or constructor)

def __init__(self,...): #_init__() 可以包含多个参数,但必须有一个self的参数,且必须为第一个参数
    pass
class TheFirstDemo:
    def __init__(self):      #仅包含 self 参数的 __init__() 构造方法,又称为类的默认构造方法
        print("调用了")
    add = 'ziyuejiaoyu'
    def say(self, content):
        print(content)

In defining the class, either explicitly created constructor class or instance method is added to the class, require that the self argument as a method of first parameter

 

class Person:
    def __init__(self):           # 定义一个构造方法        
        print("执行构造方法")
    def study(self,name):          # 定义一个study()实例方法
        print(name,"正在学Python")

A class body, according to the position of the different variable definition, and the definition of different ways, property class can be subdivided into the following three types:

  • Class body, outside of any function: range defined variables, called class property or class variable;
  • Class body, the internal functions: variables. "Self variable names" in the definition, called instance variables or instance attributes;
  • Class body, all internal functions: variables "variable name = variable value" is defined is referred to as local variables.

 

 

 

Published 96 original articles · won praise 76 · views 40000 +

Guess you like

Origin blog.csdn.net/u010244992/article/details/104910667
Recommended