Python Chapter 17: Object-Oriented Basics

Object Oriented Foundation

Class: A class is a collection of objects with the same functions and properties. (Class is abstract)

Object: An instance of a class is an object (object is concrete)

Define the class-through code to describe clearly which objects you have the same properties and which functions

Syntax:
class class name:
class description document
class content (class attributes and class methods)

Create object

Syntax:
class name ()

class Circle:
    pi = 4.1315926

    def __init__(self):
        self.r = 0

    def area(self):
        print(Circle.pi*self.r**2)

    def perimeter(self):
        print(2*Circle.pi*self.r)

# 创建两个Student类的对象
s1 = Student()
s2 = Student()
print(s1 is s2)    # False
print(id(s1), id(s2))
print(s1)
print(s2)

=============== Construction method and initialization

What is a constructor (function)

The name is the same as the class, and the function is a function to create an object of the corresponding class.

When python defines a type, the system will automatically create a corresponding construction method for this class

Magic method: The functions that start with __ and end with __ in the class are collectively called magic methods. This type of method does not require the programmer to call, the system will automatically call it when appropriate

Initialization method: _ init _

When creating an object through a class, the system will automatically call the __init__ method in this class

When adding the __init__ method to the class, as long as the method name and the default parameter self are not changed, the programmer can add parameters and function body at will according to the situation

When calling the constructor to create an object, no parameters are needed. Several parameters are needed. See if the __init__ method in the corresponding class has additional formal parameters other than self. There are several

========== Class attributes

The attributes in the class are divided into: class attributes (fields of the class) and object attributes

Class attribute

Definition: directly define the variables outside the function in the class.
Features: not different because of different objects.
How to use: class name. class attribute

Object attributes

Definition: In the __init__ function, it is defined in the form of'self.attribute name=value'.
Features: it will be different because of different
objects. How to use: object.object attribute

class Person:
    a = 10

    def __init__(self):
        self.name = '张三'
        self.age = 18
        self.gender = '男'
class Dog:
    def __init__(self, name, color, gender='母狗', breed='土狗'):
        self.name = name   # 每次创建狗的对象的时候必须给name属性传参
        self.gender = gender  # 每次创建狗的对象的时候可以不给gender赋值,也可以给gender赋值。如果不赋值默认值是'母狗'
        self.age = 1      # 每次创建狗的对象的时候age的值只能是1
        self.color = color
        self.breed = breed

    # __repr__魔法方法:打印当前类的对象的时候,系统会自动调用这个方法,并且把这个方法的返回值作为打印结果(返回值必须是字符串)
    def __repr__(self):
        # self: 打印谁self就指向谁
        # return str(self.__dict__)
        return f'<{str(self.__dict__)[1:-1]}>'

d1 = Dog('大黄', '黄色')
print(d1.name, d1.color, d1.gender, d1.age, d1.breed)

d2 = Dog('小白', '白色', breed='哈士奇')
print(d2)

====================== Class method

The functions defined in the class are methods. The methods in the class are divided into: object methods, class methods, static methods

Object method

How to define: The function directly defined in the class is the object method (no decorator is added before the function is defined)
Features: self-parameter self; parameter self does not need to be passed when calling, the system will automatically pass the current object to self (who Whoever calls self)

list
list1 = [100,20]
list1.append(42)
print(list1)    [100,20,40]
此处append后有两个参数,其中一个就是self,不给值,list1.了这个对象,self就指向list1

How to call: call through the form of object. method name ()
When to use: if object properties are needed to implement the function of the function

练习:定义一个点类(二维),有属性: x坐标、y坐标  方法:计算当前点到指定点的距离
class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def distance(self,self2):
        return ((self.x-self2.x)**2+(self.y-self2.y)**2)**0.5


p1 = Point(10,20)
p2 = Point(20,30)
result = p1.distance(p2)
print(result)

Guess you like

Origin blog.csdn.net/SaharaLater/article/details/111935437