Object-oriented: Simple use of Python classes

01. dirBuilt-in functions

  • In Pythonthe subject is almost ubiquitous , before we learn the variables , data , functions are objects

In Pythoncan be verified using the following two methods:

  1. The identifier / data input after a .press TABbutton, iPythonyou will be prompted to call the object can be a list of method
  2. Built-in functions using dirthe incoming identifier / data , the object can be viewed in all the properties and methods

Tip __方法名__ format is to Pythonprovide a built-in method / property , will give you some common built-in methods / properties later

Serial number Method name Types of effect
01 __new__ method Create an object , the will is automatically invoked
02 __init__ method The object is initialized when, will be automatically invoked
03 __del__ method The object is destroyed from memory before, will be automatically invoked
04 __str__ method Returns the description information of the object , the printfunction output uses

Tips make good use of dir()the function, in the study do not need to memorize a lot of content

02. Define a simple class

Object-oriented is more of the package , the package multiple methods in a class , which is created out through the class object, you can call these methods directly !

2.1 Define a class that only contains methods

  • In Pythonthe method to define a class that contains only, the following syntax:
class 类名:

    def 方法1(self, 参数列表):
        pass
    
    def 方法2(self, 参数列表):
        pass
  • The definition format of the method is almost the same as the function learned before
  • The difference is that the first parameter must be self, please remember it for now, and introduce it laterself

Note: The name of the class naming conventions to meet the large hump nomenclature

2.2 Create objects

  • When a class is defined, use this class to create an object, the syntax format is as follows:
对象变量 = 类名()

2.3 Case

demand

  • Kittens love to eat fish, the kitten to drink water

analysis

  1. Define a cat Cat
  2. Defines two methods, eatanddrink
  3. On demand-no need to define attributes
class Cat:
    """这是一个猫类"""

    def eat(self):
        print("小猫爱吃鱼")

    def drink(self):
        print("小猫在喝水")

tom = Cat()
tom.drink()
tom.eat()

Emphasis on referenced concepts

In object-oriented development, the concept of reference is equally applicable!

  • In Pythonuse the class after creating objects , tomvariables are still recorded address of the object in memory
  • That is, tomvariable references a new cat objects
  • Use printoutput object variable , by default, is capable of outputting the variable object references are made which created a class object , as well as an address in memory ( hexadecimal )

Tip: In the computer, usually hexadecimal representation memory address

  • %dCan output numbers in decimal
  • %xCan output numbers in hexadecimal

03. The method of selfparameter

3.1 Add attributes to objects

  • In the Pythonmiddle, you want to set the properties to objects , very easy, but not recommended
    • Because: the encapsulation of object properties should be encapsulated inside the class
  • Only need external code class directly in .setting a property to

Note: Although this method is simple, it is not recommended!

tom.name = "Tom"
...

lazy_cat.name = "大懒猫"

3.2 selfIn the internal methods the output of each cat's name

Of which object method call, in the method selfis a reference to an object which

  • Within a method class package, selfsays the current method of calling object itself
  • When you call a method , programmers do not need to pass selfparameters
  • Inside the method
    • You can self. access the object's properties
    • You can also self. call other object methods
  • The transformation code is as follows:
class Cat:

    def eat(self):
        print("%s 爱吃鱼" % self.name)

tom = Cat()
tom.name = "Tom"
tom.eat()

lazy_cat = Cat()
lazy_cat.name = "大懒猫"
lazy_cat.eat()
  • In class outside , through the 变量名.access object properties and methods
  • In the type of packaging method , by self.accessing the object properties and methods

04. Initialization method

4.1 Add attributes to objects outside the class

  • Adjust the case code, call the method first, then set the properties , and observe the execution effect
tom = Cat()
tom.drink()
tom.eat()
tom.name = "Tom"
print(tom)
  • The program execution error is as follows:
AttributeError: 'Cat' object has no attribute 'name'
属性错误:'Cat' 对象没有 'name' 属性

prompt

  • In the daily development, it is not recommended outside of class to the object increase property
    • If the attribute is not found at runtime, the program will report an error
  • It should contain objects which attributes should be encapsulated in the interior of the class

4.2 Initialization method

  • When 类名()the object is created, it will automatically do the following:
    1. In memory for the object allocated space - creating an object
    2. Property of the object set initial values - initialization method ( init)
  • The initialization method is the __init__method, __init__the object of the built-in method

__init__The method is specifically used to define a class method which properties have !

The Catincrease __init__method, verify that the method is called automatically when you create an object

class Cat:
    """这是一个猫类"""

    def __init__(self):
        print("初始化方法")

4.3 Define properties inside the initialization method

  • In the __init__interior of use self.属性名 = 属性的初始值can be defined properties
  • After defining attribute, and then use the Catclass to create objects, you will own the property
class Cat:

    def __init__(self):

        print("这是一个初始化方法")
        
        # 定义用 Cat 类创建的猫对象都有一个 name 的属性
        self.name = "Tom"

    def eat(self):
        print("%s 爱吃鱼" % self.name)

# 使用类名()创建对象的时候,会自动调用初始化方法 __init__
tom = Cat()

tom.eat()

4.4 Set initial value while initializing

  • In development, if you want to simultaneously create an object, you set the properties of an object , it can __init__be a method transformation
    1. The desired value of the property set, defined as the __init__parameters of the method
    2. In the method using the internal self.属性 = 形参parameters received external transmission
    3. When you create an object, use 类名(属性1, 属性2...)call
class Cat:

    def __init__(self, name):
        print("初始化方法 %s" % name)
        self.name = name
    ...
    
tom = Cat("Tom")
...

lazy_cat = Cat("大懒猫")
...

05. Built-in methods and properties

Serial number Method name Types of effect
01 __del__ method The object is destroyed from memory before, will be automatically invoked
02 __str__ method Returns the description information of the object , the printfunction output uses

5.1 __del__Method

  • In Pythonthe

    • When you use 类名()when you create an object, the object is complete allocation of space , the automatic calling __init__method
    • When an object is destroyed from memory before, it will automatically call the __del__method
  • Application scenarios

    • __init__ Transform the initialization method to make the creation of objects more flexible
    • __del__If you want to before the object is destroyed, do some things that you can consider __del__methods
  • life cycle

    • An object from a call to 类名()create the life cycle begins
    • An object __del__once the method is called, the end of the life cycle
    • During the life cycle of the object, you can access the object properties, or let the object call methods
class Cat:

    def __init__(self, new_name):

        self.name = new_name

        print("%s 来了" % self.name)

    def __del__(self):

        print("%s 去了" % self.name)

# tom 是一个全局变量
tom = Cat("Tom")
print(tom.name)

# del 关键字可以删除一个对象
del tom

print("-" * 50)

5.2 __str__Method

  • In Pythonusing printthe output object variable , by default, this variable will be output object references are made which created a class object , as well as an address in memory ( hexadecimal )
  • If in development, want to use the printoutput object variables , it is possible to print customized content , you can use __str__the built-in method of

Note: the __str__method must return a string

class Cat:

    def __init__(self, new_name):

        self.name = new_name

        print("%s 来了" % self.name)

    def __del__(self):

        print("%s 去了" % self.name)

    def __str__(self):
        return "我是小猫:%s" % self.name

tom = Cat("Tom")
print(tom)

Guess you like

Origin blog.csdn.net/david2000999/article/details/112918049