Python OOP: Object-oriented basics, define classes, create objects/instances, self, create multiple objects, add object attributes, access object attributes, __init__ method, __init__ with parameters, __str__ method, __del__ method

One, understand object-oriented

Object-oriented is an abstract programming idea, a kind of idea found in many programming languages.

  • The orientation object is to treat programming as a thing, and to the outside world, things are used directly, regardless of their internal situation. Programming is to set up what things can do.
  • In the process of face-to-object programming, there are two important components: class and object.
  • The relationship between class and object: Use class to create an object. (Instantiate)

Class is a general term for a series of things with the same characteristics and behaviors, and it is an abstract concept.

  • Features are attributes
  • Behavior is method

A class is an abstract concept, not a real thing, an object is a real thing created by a class

Second, the object-oriented implementation method

1. Define the class:
Insert picture description here2. Create an object : The process of creating an object is also called instantiating an object.
Insert picture description here

# 定义people类
class People():
    def person(self):  # 定义实例方法
        print("person startup")
# 创建对象
p1 = People()
# 验证
print(p1) # 打印对象
p1.person() #调用对象方法--对象.方法名()

输出:
<__main__.People object at 0x000001C54AE88288>
person startup

3. Self refers to the object that calls the method.

class People():  #定义类
    def person(self):
        print("i am People class")
        print(self)
p1 = People()  # 创建对象
print(p1)
print("-"*40)
p1.person() #对象调用方法

输出:
<__main__.People object at 0x0000026422AF8308>
----------------------------------------
i am People class
<__main__.People object at 0x0000026422AF8308>  #self的内存地址与对象p1的内存地址相同,所以self是调用该函数的对象

4. Create multiple objects in one class

  • A class can create any number of objects
  • Each object is a different object with different memory addresses
# 需求:1,一个类创建多个对象,2,多个对象都调用函数的时候,self地址是否相同
class People():
    def person(self):
        print("i am coming")
        print(self)

p1 = People()
p1.person()

p2 = People()
p2.person()

输出:
i am coming
<__main__.People object at 0x0000026C3D1E8288>
i am coming
<__main__.People object at 0x0000026C3D1EFE88>

5. Adding object attributes
Attributes are characteristics. Object attributes can be added and obtained outside the class, and can also be added and obtained on the class surface.
5.1, add attributes outside the class
Insert picture description here
5.2, access object attributes outside the class
Insert picture description here

class People():
    def person(self):
        print("i am coming")

p1 = People()
p1.height = 180
p1.weight = 170
print("p1的身高是{}cm,体重是{}斤。".format(p1.height, p1.weight))

输出:p1的身高是180cm,体重是170斤。

5.3. Access object properties in the class Inside
: the position of the class indentation
Insert picture description here

class People():
    def person(self):
        print("i am coming")
    def print_info(self):
        print("p1的身高是{}cm,体重是{}斤。".format(self.height, self.weight))

p1 = People()
p1.height = 180
p1.weight = 170

p1.print_info()

输出:p1的身高是180cm,体重是170斤。

5.4 Invoking class methods in a class

Syntax: self. method name()

class People:
    def person(self):
        return "i am coming."
    
    def info(self):
        return "hi,"
    
    def personinfo(self):
        print(self.info(), self.person())


p1 = People()
p1.personinfo()

输出:
hi, i am coming

6. Magic method: init () method
In Python, xx () functions are called magic methods, which refer to functions with special functions.
Thinking: The width and height of an object are inherent attributes. Can these attributes be assigned during the creation process?
Answer: It should be. The role of the
init () method: to initialize the object.

  • The init () method is called by default when an object is created, and does not need to be manually called
  • The self parameter in init (self) does not need to be passed by the developer, the python interpreter will automatically pass the current object reference.
class People():  # 定义类
    def __init__(self):  # 定义init方法,初始化功能
        self.height = 180  # 添加实例属性
        self.weight = 170

    def print_info(self):  # 定义实例方法
        print("身高是{}cm,体重是{}".format(self.height, self.weight))  # 在类里面访问实例属性

p1 = People()
p1.print_info()

输出:身高是180cm,体重是170

7.
Thinking of __init__() with parameters : One class creates multiple objects, and different objects set different initialization properties?
Answer: Pass parameters.

class People():
    def __init__(self, height, weight):  # 定义init方法,初始化实例属性,方法里有两个形参,height形参,weight形参
        self.height = height  # self.height是实例的属性,height是形参
        self.weight = weight  # self.weight是实例的属性,weight是形参

    def print_info(self):  #定义实例方法
        print("身高是{}cm,体重是{}斤。".format(self.height, self.weight))
        # 此处的self.height是实例的属性,self.weight是实例的属性


p1 = People(180, 170)  # 创建实例时传入实参
p1.print_info()  # 调用实例方法

p2 = People(165, 100)
p2.print_info()

输出:
身高是180cm,体重是170斤。
身高是165cm,体重是100斤。

If no parameters are passed when creating an instance, an error will be reported:
Insert picture description here

8. The magic method __str__()

  • When using print to print the object name without parentheses, the memory address of the object is printed by default.
  • If the class defines the str method, then the return data in this method will be printed.
  • The str () method generally puts explanation text
  • Note: str () method, use the return keyword, write the content to be returned later, use print when calling
class People():
    def __init__(self, height, weight):  # 定义init方法,初始化属性,方法里有两个形参
        self.height = height  # self.height是实例的属性,height是形参
        self.weight = weight  # self.weight是实例的属性,weight是形参

    def print_info(self):  #定义实例方法
        print("身高是{}cm,体重是{}斤。".format(self.height, self.weight))
        # 此处的self.height是实例的属性,self.weight是实例的属性

p1 = People(180, 170)  # 创建实例时传入实参
print(p1)

输出:<__main__.People object at 0x0000020D3888FE88>
 # 当使⽤print打印对象名不加括号的时候,默认打印对象的内存地址。
class People():
    def __init__(self, height, weight):  # 定义init方法,初始化属性,方法里有两个形参
        self.height = height  # self.height是实例的属性,height是形参
        self.weight = weight  # self.weight是实例的属性,weight是形参

    def print_info(self):  #定义实例方法
        print("身高是{}cm,体重是{}斤。".format(self.height, self.weight))
        # 此处的self.height是实例的属性,self.weight是实例的属性

    def __str__(self):
        return "这是__str__方法解释说明文字,类的说明,对象状态说明"


p1 = People(180, 170)  # 创建实例时传入实参
print(p1)

输出:这是__str__方法解释说明文字,类的说明,对象状态说明

9. The magic method __del__()

  • When deleting an object, the python interpreter will also call the del () method by default .
  • When the object is not deleted manually, the __del__ method will be automatically called as long as the program runs from top to bottom, and the memory will delete the variables, classes, objects, etc., when the program is running, and release the memory
class People():
    def __init__(self):
        self.width = 300
        
    def __del__(self):
        print("was deleted!")

p1 = People()

输出:was deleted!

3. Basic summary

Think about the total number of things that participate in this demand. After dividing the things, classify the things, create as many classes as there are classifications, and then use classes to create objects.
Insert picture description here
Insert picture description here
Insert picture description here
Magic methods don't need to be called manually, they are called automatically when the program meets the conditions.

PS: source, bilibili

Guess you like

Origin blog.csdn.net/weixin_47008635/article/details/114497264