Python learning diary 11 - class 2

Posted by samirk on Thu, 27 Jan 2022 02:13:56 +0100

1. Three characteristics of object-oriented: encapsulation, inheritance and polymorphism
2. Encapsulation

class Car:
    def __init__(self,brand):
        self.brand = brand
    def start(self):
        print("The car has started...")

car = Car("bmw X5")
car.start()
print(car.brand)

Output result:
The car has started
BMW X5

If the attribute does not want to be accessed outside the class object, use two "" in front

#If the attribute does not want to be accessed outside the class object, use two "" in front
class Student:
    def __init__(self,name,age):
        self.name = name
        self.__age = age    #Age doesn't want to be used outside the class, so two '' are added in front of it
    def show(self):
        print(self.name,self.__age)   #But it can be used internally

stu = Student("Zhang San",20)
stu.show()      #Can be used internally
print(stu.name)
#print(stu.__age)    #An error is reported. age cannot be used outside the class

Output result:
Zhang San 20
Zhang San

But if you really want to use age outside the class, you can_ Student__age access

#But if you really want to use age outside the class, you can_ Student__age access
print(stu._Student__age)   #Whether it is used or not depends entirely on the consciousness of programmers

Output result:
20

3. Inherit
3.1
If a class does not inherit any classes, it inherits object by default
In the following program, both Student and Teacher inherit Person
In the inherited classes, pay attention to the writing of init

#If a class does not inherit any classes, it inherits object by default
class Person(object):   #Person inherits the object class, (object) can be omitted without writing
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def info(self):
        print(self.name,self.age)

class Student(Person):       #Student inherits Person
    def __init__(self,name,age,stu_no):
        super().__init__(name,age)
        self.stu_no = stu_no
    def info(self):       #Method overrides in subclasses
        super().info()
        print("Student number",self.stu_no)    #Remember to write self

class Teacher(Person):      #Teacher inherits Person
    def __init__(self,name,age,yearofteacher):
        super().__init__(name,age)
        self.yearofteacher = yearofteacher
    def info(self):
        super().info()        #Subclass overridden methods can be overridden through super() Xxx() calls the overridden method in the parent class
        print("Teaching age",self.yearofteacher)    #Remember to write self
stu = Student('Zhang San',24,'2016')
teacher = Teacher('Li Si',35,10)

stu.info()
teacher.info()

Output result:
Zhang san24
Student No.: 2016
Li Si 35
Teaching age 10

3.2 multiple inheritance is allowed, such as

class A(object):
    pass
class B(object):
    pass
class C(A,B):     #C inherited A and B
    pass

3.3 method rewriting
If a subclass is not satisfied with a property or method inherited from the parent class, it can rewrite it (method body) in the subclass
Subclass overridden methods can be overridden through super() Xxx() calls the overridden method in the parent class

For example, the info(self) method of the following two subclasses

class Student(Person):       #Student inherits Person
    def __init__(self,name,age,stu_no):
        super().__init__(name,age)
        self.stu_no = stu_no
    def info(self):       #Method overrides in subclasses
        super().info()    #Call the overridden method in the parent class
        print("Student number",self.stu_no)    #Remember to write self

class Teacher(Person):      #Teacher inherits Person
    def __init__(self,name,age,yearofteacher):
        super().__init__(name,age)
        self.yearofteacher = yearofteacher
    def info(self):     #Method overrides in subclasses
        super().info()    #Call the overridden method in the parent class
        print("Teaching age",self.yearofteacher)    #Remember to write self

3.4 object class
If a class does not inherit from other classes, it inherits the object class by default. Therefore, all classes will have the properties and methods of the object class
The built-in function dir() can view all properties of the specified object

class Student:
    pass
stu = Student()
print(dir(stu))    #Output all attributes inherited from the object class

Output result:
['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref']
(there is an underscore _ before and after each attribute, which cannot be displayed here)

There is one in the object_ str_ () method to return a description of the object

#There is one in the object_ str_ () method to return a description of the object

class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __str__(self):
        return "My name is{0},this year{1}year".format(self.name,self.age)

stu = Student("Lin Xinqi",20)
print(stu)   #Called by default__ str__ Such a method

Output result:
My name is Lin Xinqi. I'm 20 years old

4. Polymorphism

class Animal:
    def eat(self):
        print("Animals can eat")
class Dog(Animal):
    def eat(self):
        print("Dogs eat bones...")
class Cat(Animal):
    def eat(self):
        print("Cats eat fish...")

class Person:
    def eat(self):
        print("People eat cereals")

def fun(obj):
    obj().eat()

fun(Animal)
fun(Dog)
fun(Cat)
fun(Person)

Output result:
Animals can eat
Dogs eat bones
Cats eat fish
People eat cereals

5. Special attributes are added before and after__ of

class A:
    pass
class B:
    pass
class C(A,B):
    def __init__(self,name,age):
        self.name = name
        self.age = age
class D(A):
    pass
x = C('Jack',20)
print(x.__dict__)    #Output attribute dictionary of instance object
print(C.__dict__)

Output result:
{'name': 'Jack', 'age': 20}
{'module': 'main', 'init': <function C.init at 0x0000016D674595E8>, 'doc': None}

print(x.__class__)      #Class to which the output object belongs < class'__ main__. C'>
print(C.__bases__)    #Elements of the parent type of class C
print(C.__base__)    #Base class of class (whoever writes in front will output)
print(C.__mro__)   #Hierarchy of output classes
print(A.__subclasses__())   #View subclasses of A

Output result:
<class 'main.C'>
(<class 'main.A'>, <class 'main.B'>)
<class 'main.A'>
(<class 'main.C'>, <class 'main.A'>, <class 'main.B'>, <class 'object'>)
[<class 'main.C'>, <class 'main.D'>]
(the underline _ of the above results cannot be displayed)

6. Special methods are added before and after__ Method of

class Student:
    def __init__(self,name):
        self.name = name

    def __add__(self,other):
        return self.name+other.name    #If you want two objects to have the function of adding, you need to write__ add__ This special method

    def __len__(self):
        return len(self.name)
stu1 = Student("Zhang San")
stu2 = Student("Li Si")
stu3 = Student("Jack")

s = stu1+stu2   #It implements the addition operation of two objects (because in the Student class, write the special method _add_ ()
print(s)
s = stu1.__add__(stu2)   #The effect is the same as above
print(s)

Output result:
this one and that one
this one and that one

lst = [11,22,33,44]
print(len(lst))
print(lst.__len__())

print(len(stu1))   #When len is not defined, an error will be reported. Define the method in the class
print(len(stu3))

Output result:
4
4
2
4

7,

class CPU:
    pass
class Disk:
    pass
class Computer:
    def __init__(self,cpu,disk):
        self.cpu = cpu
        self.disk = disk

7.1 assignment of variables

cpu1 = CPU()
cpu2 = cpu1
print(cpu1,id(cpu1))
print(cpu2,id(cpu2))

Output result:
<main.CPU object at 0x000001BA0E0B73C8> 1898611176392
<main.CPU object at 0x000001BA0E0B73C8> 1898611176392

Shallow copy of class 7.2

disk = Disk()
computer = Computer(cpu1,disk)
#At the beginning of shallow copy, only the instance object computer is copied, and the child objects cpu and disk in it are not copied (therefore, the addresses of computer and computer2 are different, and the addresses of cpu and disk will be the same)
import copy
computer2 = copy.copy(computer)
print(computer,computer.cpu,computer.disk)
print(computer2,computer2.cpu,computer2.disk)

Output result:
<main.Computer object at 0x000001BA0E0B74C8> <main.CPU object at 0x000001BA0E0B73C8> <main.Disk object at 0x000001BA0E0B7548>
<main.Computer object at 0x000001BA0E0B7588> <main.CPU object at 0x000001BA0E0B73C8> <main.Disk object at 0x000001BA0E0B7548>

The deep copy of class 7.3 not only copies the instance object, but also copies the sub objects cpu and disk

computer3 = copy.deepcopy(computer)
print(computer,computer.cpu,computer.disk)
print(computer3,computer3.cpu,computer3.disk)

Output result:
<main.Computer object at 0x000001BA0E0B74C8> <main.CPU object at 0x000001BA0E0B73C8> <main.Disk object at 0x000001BA0E0B7548>
<main.Computer object at 0x000001BA0E0B7608> <main.CPU object at 0x000001BA0E0B7648> <main.Disk object at 0x000001BA0E0B7688>

The results show that the addresses of the three variables are different

Topics: Python Back-end