python initialization method is called automatically when you create an object

Python create an object: Object Name = class ()

class Point:
    pass
p1 = Point()
p2 = Point()

When creating an object, Python interpreter automatically performs the following operations:
1. Create Object ---- space allocated for the object in memory;
2. initialization method (init) - set initial values for the attribute object
initialization method: the init , It belongs to the built-in method to indicate the behavior of an object is initialized
to create an initialization method example:

class Cat():
      def __init__(self):    #类方法必须要添加self
          print('这是一个初始化方法')
tom=Cat()  #实例化对象时会自动调用__init__方法

In the initialization method defined inside properties
define properties: __init__ method used internally self attribute name = initial value of the property.
Use: property class where the initial definition, it is possible to call the property
Example:

class Cat():
      def __init__(self):    #类方法必须要添加self
          print('这是一个初始化方法')
          self.gender="女"   #定义gender属性的初始值
tom=Cat()  #实例化对象时会自动调用__init__方法
print(tom.gender)

NOTE: ①Python interpreter consists of a compiler and a virtual mechanism, the compiler is responsible for converting the source code into byte code file, and responsible for implementing the virtual machine bytecode.
So, in fact, have interpreted language compilation process, but this process is not directly generate compiled object code, but the intermediate code (bytecode), and then through the virtual machine bytecode interpreted line by line
② Method Description
__init __ constructor, initializing a class, the class is enabled when executed will

Welcome to exchange knowledge with Python

Released three original articles · won praise 1 · views 85

Guess you like

Origin blog.csdn.net/qq_36510630/article/details/104025477