(1) Getting to know object-oriented
Python fully adopts the idea of object-oriented, is a real object-oriented programming language, fully supports the basic functions of object-oriented, such as: inheritance, polymorphism, encapsulation, etc.
Python
supports multiple programming
paradigms .
In Python
, everything is an object. The data types, functions, etc. we learned earlier are all objects.
object-oriented features
The idea of object-oriented programming (
Object oriented Programming
,
OOP
) is mainly designed for large-scale software.
Object-oriented programming makes the program more extensible and readable, making programming as easy as building blocks.
Object-oriented programming encapsulates data and methods related to operating data into objects, and the way of organizing code and data is closer to human thinking, thus greatly improving the efficiency of programming.
The difference between procedural and object oriented
Process-oriented and object-oriented are both ideas of software analysis, design and development
,
which guide people to analyze, design and develop software in different ways. C
language is a typical process-oriented language, and Java
is a typical object-oriented language.
What is process-oriented?
Process-oriented is suitable for simple, non-cooperative transactions, focusing on how to execute. When we are process-oriented, we first think about "
how to implement it step by step?". For example, how to drive? We can easily list the implementation steps:
But when we think about more complex design tasks, such as
"
how to build a car?
" , we will find
that it is impossible to list such steps as
1234 .
That's because building a car is too complicated and requires a lot of collaboration to complete. At this time, object-oriented thinking came into being.
What is object-oriented?
Object-oriented
(Oriented-Object)
thinking is more in line with people's thinking mode. The first thing we think about is "
how to design this thing?
"
. For example, when thinking about building a car, we will first think about
"
how to design a car?"
rather than
"
how to build a car step by step
"
. This is a shift in mindset. Naturally, we start
thinking about "
what is a car made of ": car: body, engine, accelerator, steering wheel...
In order to cooperate, we found a tire factory to complete the steps of manufacturing tires, and an engine factory to complete the steps of manufacturing engines; in this way, we found that everyone can manufacture cars at the same time, and finally assemble them, which greatly improves efficiency. Specific to an assembly line operation in a tire factory, there are still steps, and it is still inseparable from the executor and process-oriented!
Object-oriented can help us grasp and analyze the whole system from a macro perspective. However, when it comes to the micro-operations of the implementation part (that is, each method), it still needs to be handled in a process-oriented way.
Object-oriented and process-oriented summary
1
Both are problem-solving ways of thinking, and both are ways of code organization.
2
Process-oriented is a kind of
"
performer's thinking
"
, to solve simple problems can use process-oriented
3
Object-oriented is a kind of
"
designer's thinking
"
. To solve complex and collaborative problems, you can use object-oriented
Object-oriented cannot be separated from process-oriented:
Macroscopically: overall design through object-oriented
Micro: execute and process data, still process-oriented
(2) Object
As the problems faced by programming become more and more complex, the programming language itself is also evolving. Starting from mainly processing simple data, " arrays
"
evolve as the data increases; data types become more complex, and " structures "
evolve
; processing data The method and logic become more complicated, and "objects" are evolved .
simple data
Numbers like
30, 40
,
50.4
, etc. can be regarded as simple data. The very first computer programs were programmed with numbers like this.
2
Arrays in C language
Group data of the same type together. For example: integer array
[20,30,40]
, floating point array
[10.2, 11.3, 12.4]
, string array:
["aa", "bb", "cc"]
,
above [20,30,40]
Not
a list in
python , but
an array in C
3
Structures in C language
Putting different types of data together is
a data structure in
C language.
for example:
struct resume{
int age;
char name[10];
double value;
};
4
object
Putting different types of data and methods (that is, functions) together is an object. for example:
class Student:
company = "SXT" #类属性
count = 0 #类属性
def __init__(self,name,score):
self.name = name #实例属性
self.score = score
Student.count = Student.count+1
def say_score(self): #实例方法
print("我的公司是:",Student.company)
print(self.name,'的分数是:',self.score)
object complete memory structure
Classes are abstract, also known as
"
object templates
"
. We need to create an instance object of the class through the template of the class, and then we can use the functions defined by the class. We said earlier that a Python
object contains three parts:
id
(
identity
identification code),
type
(object type),
value
(object value). We can go a step further and say that a Python
object consists of the following parts:
(3) Class definition
A class can be regarded as a template, or a drawing, and the system creates objects according to the definition of the class. We want to build a car, how to build it? The class is this drawing, which specifies the detailed information of the car, and then the car is built according to the drawing.
Class: We call it
class
. Object: We call
object
,
instance
(
instance
)
. In the future, an object of a certain class is an instance of a certain class. It means the same thing.
properties and methods
We define the properties (data) and methods (behavior) of data types through classes
,
that is, "
classes package behavior and state together
"
.
An object is a concrete entity of a class, generally called an
"
instance of a class
"
. The class is regarded as a
"
biscuit mold
" , and the object is the
" biscuit " manufactured
according to this "
mold
" .
When objects are created from a class, each object shares the behavior of the class (methods defined in the class), but has its own property values (no shared state). To be more specific: "
method code is shared, property data is not"
.
Take the student class as an example
In Python
,
"
everything is an object
"
. A class is also called a
"
class object
"
, and an instance of a class is also called an "
instance object
"
.
The syntax for defining a class is as follows:
class
class name:
Class body
The main points are as follows:
-
Class names must conform to the rules of " identifiers " ; generally, the first letter is capitalized, and multiple words use the " camel case principle " .
-
In the class body we can define properties and methods
-
Attributes are used to describe data, and methods ( that is, functions ) are used to describe operations related to these data
A typical class definition:
class Student:
def __init__(self,name,score): #构造方法第一个参数必须为self
self.name = name #实例属性
self.score = score
def say_score(self): #实例方法
print("{0}的分数是{1}".format(self.name,self.score))
s1 = Student('王老五',80) #s1是实例对象,自动调用__init__()方法
s1.say_score()
pass is an empty statement. It means to do nothing, just exist as a placeholder. When you write code, if you don’t know what to add to a method or class, you can use pass to fill in the space first, and then add it later.
__init__ constructor and __new__ method
To initialize the object, we need to define the constructor
__init__()
method. The construction method is used to perform the "
initialization work of the instance object
"
, that is, after the object is created, the relevant properties of the current object are initialized, and there is no return value.
The main points of __init__()
are as follows:
-
The name is fixed and must be: __init__()
-
The first parameter is fixed and must be: self . self refers to the instance object just created
-
Constructors are usually used to initialize instance attributes of instance objects, the following code is to initialize instance attributes: name and score
def __init__(self,name,score):
self.name = name #实例属性
self.score = score
-
Call the constructor by "
class name
(
argument list
)" .
After calling, return the created object to the corresponding variable.
-
__init__()
method: initialize the created object, initialization refers to:
"
assign value to the instance attribute"
-
__new__()
method
:
used to create objects, but we generally do not need to redefine this method
-
If we don't define
the __init__
method, the system will provide a default
__init__
method.
If we define an __init__ method
with parameters
, the system does not create a default
__init__
method
The self
in
Python is equivalent to the self pointer in C++ , and the this keyword in JAVA and C# . In Python , self must be the first parameter of the constructor, and the name can be modified arbitrarily. But the general practice is called self.
instance properties and instance methods
instance attribute
Instance attributes are attributes belonging to instance objects, also known as
"
instance variables
"
. His use has the following key points:
Instance attributes are generally defined by the following code in
the __init__()
method:
self. instance attribute name = initial value
In other instance methods of this class, it is also
accessed through
self :
self.Instance attribute name
3
After creating the instance object, access it through the instance object:
obj01 = class name ()
#Create
and initialize objects, call
__init__() to
initialize properties
obj01.Instance attribute name = value
#You
can assign values to existing attributes, or add new attributes
class Student:
def __init__(self,name,score):
self.name = name #增加name属性
self.score = score #增加score属性
def say_score(self):
self.age = 18 #增加age属性
print("{0}的分数是{1}".format(self.name,self.score))
s1 = Student("张三",80)
s1.say_score()
print(s1.age)
s1.salary = 3000 #s1对象增加salary属性
s2 = Student("李四",90)
s2.say_score()
print(s2.age)
instance method
An instance method is a method that belongs to an instance object. The definition format of an instance method is as follows:
def
method name
(
self
[,
parameter list
])
:
function body
The calling format of the method is as follows:
Object.MethodName([Argument List])
Main points:
When defining an instance method, the first parameter must be
self
. As before,
self
refers to the current instance object.
When calling an instance method, you don't need and can't
pass parameters to
self .
self is automatically passed by the interpreter
The difference between functions and methods
They are all statement blocks used to complete a function, and they are essentially the same.
When the method is called, it is called through the object. Methods belong to specific instance objects, ordinary functions do not have this feature
Intuitively, the method definition needs to pass
self
, the function does not need
The essence of the method call of the instance object
other operations
dir(obj)
can get all the properties and methods of the object
1
obj.__dict__
object's attribute dictionary
2
pass
empty statement
3
isinstance (object, type)
to determine whether the
"
object
"
is
"
specified type
"
(4) Class objects, class attributes, class methods, static methods
class object
In the class definition format we mentioned earlier,
class class name:
. In fact, when the interpreter executes
the class
statement, it creates a class object
Specific code:
class Student:
pass #空语句
print(type(Student))
print(id(Student))
Stu2 = Student
s1 = Stu2()
print(s1)
Specific effect:
As can be seen from the figure, an object whose variable name is the class name
Student
is actually generated . We can also implement related calls
by assigning values to the new variable
Stu2 .
Note, the " class object "
is indeed created
.
class attribute
A class attribute is an attribute belonging to a
"
class object
"
, also known as a
"
class variable
"
. Because class attributes belong to class objects and can be shared by all instance objects.
How class attributes are defined:
class
class name:
class variable name
=
initial value
In the class or outside the class, we can
read and write through:
class name. class variable name
Memory analysis instance object and class object creation process
Let's take the following code as an example to analyze the entire creation process. The code is as follows:
class Student:
company = "仁和堂" # 类属性
count = 0 # 类属性
def __init__(self, name, score):
self.name = name # 实例属性
self.score = score
Student.count = Student.count + 1
def say_score(self): # 实例方法
print("我的公司是:", Student.company)
print(self.name, '的分数是:',self.score)
s1 = Student('李白', 80) # s1是实例对象,自动调用__init__()方法
s2 = Student('张三', 70)
s1.say_score()
print('一共创建{0}个Student对象'.format(Student.count))
class method
A class method is a method that belongs to a
"
class object
"
. Class methods are defined by the decorator
@classmethod
in the following format:
@classmethod
def
class method name
(
cls
[
, parameter list
])
:
method body
The main points are as follows:
@classmethod
must be on the line above the method
The first
cls
must have;
cls
refers to the
"
class object
"
itself
Call class method format:
class name. class method name (parameter list)
. In the parameter list, it is not necessary or possible to
pass a value to
cls
Accessing instance properties and instance methods in class methods will cause errors
When the subclass inherits the parent class method, the incoming
cls
is the subclass object, not the parent class object
Specific code:
class Student:
company = "SXT" #类属性
@classmethod
def printCompany(cls):
print(cls.company)
Student.printCompany()
static method
Python
allows the definition
of methods that have nothing to do with
"
class objects
" , called
" static methods " . "Static method " is no different from defining ordinary functions in a module, except that " static method " is placed in "class name space " and needs to be called through " class " .
Static methods are defined by the decorator
@staticmethod
in the following format:
@staticmethod
def
static method name
([
parameter list
])
:
method body
The main points are as follows:
@staticmethod
must be on the line above the method
2
Call static method format:
class name. static method name (parameter list)
3
Accessing instance properties and instance methods in static methods will cause errors
Specific code:
class Student:
company = "SXT" # 类属性
@staticmethod
def add(a, b): # 静态方法
print("{0}+{1}={2}".format(a,b,(a+b)))
return a+b
Student.add(20,30)
(5) Destructor ( __del__ method ) and garbage collection mechanism
destructor
__del__()
is called a
"
destructor
"
and is used to implement the operations required when an object is destroyed. For example: Release the resources occupied by the object, such as: open file resources, network connections, etc.
Python implements automatic garbage collection. When the object is not referenced (the reference count is 0),
__del__()
is called by the garbage collector
.
We can also delete objects through
the del statement
, thus guaranteeing that
__del__() is called
. The system will automatically provide
the __del__ method
, generally no custom destructor method is required
Specific code:
class Person:
def __del__(self):
print("销毁对象:{0}".format(self))
p1 = Person()
p2 = Person()
del p2
print("程序结束")
Operation result:
__call__
method and callable object
In Python
, any object that can directly apply
()
to itself and execute it is called a callable object.
Callable objects include custom functions,
Python
built-in functions, and instance objects mentioned in this section.
An object that defines
__call__() is called a
" callable object " , that is, the object can be called like a function.
This method enables the instance object to be used in the form of "
object name
()"
just like calling a normal function
.
(6) Three major characteristics of object-oriented
Python
is an object-oriented language that supports three major features of object-oriented programming: inheritance, encapsulation (hiding), and polymorphism.
Ⅰ Package
The properties and implementation details of the object are hidden, and only the necessary methods are provided externally. It is equivalent to "
encapsulating" details
"
and only exposing
"
relevant calling methods
" to the outside world.
" Encapsulation " is realized through the " private attributes and private methods "
learned earlier
.
Python
pursues a concise syntax, and there is no strict syntax-level
"
access control character"
, and it relies more on programmers to realize it consciously.
Ⅱ Inheritance
Inheritance is one of the three characteristics of object-oriented programming. Inheritance makes it easier for us to implement class extensions. Achieve code reuse without redesigning classes.
Inheritance allows subclasses to have the characteristics of the parent class, improving code reusability.
It is an incremental evolution in design. When the original parent class design remains unchanged, new functions can be added or existing algorithms can be improved.
If a new class inherits from a designed class, it directly possesses the characteristics of the existing class, which greatly reduces the difficulty of work. Existing classes are called "
parent classes or base classes"
, and new classes are called
"
subclasses or derived classes
"
.
grammatical format
Python
supports multiple inheritance, a subclass can inherit multiple parent classes. The syntax for inheritance is as follows:
class
subclass class name
(
parent class
1
[
, parent class
2
,
...])
:
Class body
Notice:
If no parent is specified in the class definition, the default parent is
the object class
. In other words,
object
is the parent class of all classes, which defines some default implementations common to all classes, such as:
__new__()
About the constructor:
The subclass does not override
__init__
, and when the subclass is instantiated, it will automatically call
the __init__
defined by the parent class .
When the subclass rewrites
__init__
, instantiating the subclass will not call
the __init__ defined by the parent class
If you rewrite
__init__
, you can use the
super
keyword to use the constructor of the parent class, or you can use the following format to call:
Parent class name.__init__(self, parameter list)
Inheritance and Overriding of Class Members
Member inheritance: Subclasses inherit all members of the parent class except the constructor. (
Private properties and private methods are also inherited
)
Method rewriting: subclasses can redefine the methods in the parent class, which will override the methods of the parent class, also known as "
overriding
"
code:
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def say_age(self):
print(self.name,"的年龄是:",self.age)
def say_name(self):
print("我是",self.name)
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)
self.score = score
def say_score(self):
print(self.name,"的分数是:",self.score)
def say_name(self): #重写父类的方法
print("报告老师,我是",self.name)
s1 = Student("张三",16,85)
s1.say_score()
s1.say_name()
s1.say_age()
print(Student.mro())
View the inheritance hierarchy of a class
The inheritance hierarchy of this class can be output through the method
mro() of the class
or the attribute
__mro__ of the class.
object root class
The object
class is the parent class of all classes, so all classes have the properties and methods of
the object
class. We obviously need to delve into the structure of
the object
class. It is very good for us to continue to learn Python in depth
.
dir()
View object properties
In order to learn more about objects, first learn the built-in function
dir()
, which allows us to easily see all the properties of the specified object
[Test] View all properties of the object and
compare with
the object
Specific code:
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)
self.score = score
def say_score(self):
print(self.name,"的分数是:",self.score)
def say_name(self): #重写父类的方法
print("报告老师,我是",self.name)
obj = object()
print(dir(obj))
s1 = Student("张三",15,85)
print(dir(s1))
Specific effect:
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'say_age', 'say_name', 'say_score', 'score']
From the above we can find the following points:
The Stuednt
object adds eight properties:
__dict__ 、
__module__ 、
__weakref__ 、
age、
name、
say_age、say_name、say_score、score
All properties of
object ,
the Student
class as a subclass of
object
obviously contains all properties
When printing
age
,
name
, and say_age
, it is found that although say_age is a method, it is actually an attribute. It's just that the type of this attribute is method .
multiple inheritance
Python
supports multiple inheritance, a subclass can have multiple
"
direct parent classes
"
. In this way, it has the characteristics of "
multiple parent classes
"
. However, since this will be
extremely complicated by the
"
overall level of the class
" , try to avoid using it.
Specific code:
class A:
def aa(self):
print("aa")
class B:
def bb(self):
print("bb")
class C(B,A):
def cc(self):
print("cc")
c = C()
c.cc()
c.bb()
c.aa()
super() gets the parent class definition
In the subclass, if we want to get the method of the parent class, we can do it through
super()
.
super()
represents the definition of the parent class, not the parent class object.
Want to call the constructor of the parent class:
super(subclass name, self).__init__(parameter list)
Specific code:
class A:
def __init__(self):
print("A的构造方法")
def say(self):
print("A: ",self)
print("say AAA")
class B(A):
def __init__(self):
super(B,self).__init__() #调用父类的构造方法
print("B的构造方法")
def say(self):
#A.say(self) 调用父类的say方法
super().say() #通过super()调用父类的方法
print("say BBB")
b = B()
b.say()
running result:
A's construction method
B's construction method
A: <__main__.B object at 0x0000014F911A9390>
say AAA
say BBB
Ⅲ Polymorphism
Polymorphism means that the same method call will produce different behaviors due to different objects. Such examples abound in life: the same way of life, but different ways of living for different things. The life of a bear is running on the ground, the life of a fish is swimming in the water, and the life of an eagle is in the blue sky. Take juicing as an example, if you put apples in, it will produce apple juice, if you put coconuts in, it will produce coconut juice, and if you put in oranges, it will produce orange juice.
Note the following two points
about polymorphism
:
Polymorphism is polymorphism of methods, properties are not polymorphic.
There are two necessary conditions
for the existence of polymorphism
: inheritance and method rewriting
Specific code:
#多态
class Animal:
def shout(self):
print("动物叫了一声")
class Dog(Animal):
def shout(self):
print("小狗,汪汪汪")
class Cat(Animal):
def shout(self):
print("小猫,喵喵喵")
def animalShout(a):
a.shout() #传入的对象不同,shout方法对应的实际行为也不同。
animalShout(Dog())
animalShout(Cat())