One 、 object-oriented
1. Objects in memory
# 1
# Be careful 1: In general , Objects created from the same class , Occupy different addresses in memory
class Person():
pass
p1 = Person()
print(id(p1))
p2 = Person()
print(id(p2))
print(p1 is p2)
# 2.
# Be careful 2: Properties of different objects with the same name , Occupy different space in memory , When the attribute value of an object is modified , It has no effect on the property values of other objects
class Person():
__slots__ = ("name",)
def __init__(self,name):
self.name = name
p1 = Person('aaa')
print(p1.name)
p2 = Person('aaa')
print(p2.name)
# Think about the problem :p1.name and p2.name Is it the same memory address ?----> Not the same memory space
# print(p1.name is p2.name) # True
# print(id(p1.name) == id(p2.name)) # True
p1.name = 'tom'
print(p1.name,p2.name)
"""
summary :
If two objects have the same address , Then the attribute values of the two objects must be the same
If the attribute values of two objects are the same , These two objects are not necessarily the same object
"""
2. Destructor 【 understand 】
Constructors : A function that is automatically called when an object is created
Contrary to constructors , Called automatically when the object is destroyed , It's called a destructor , The function is called __del__
"""
Constructors : Functions that are automatically called during object creation , Include __new__ and __init__
Destructor : A function that is called automatically when an object is destroyed ,__del__
"""
"""
【 Interview questions 】 The timing of the destructor call
"""
class Person():
def __init__(self):
print(" The constructor was called ~~~~")
def __del__(self):
print(" The destructor was called ~~~~")
# 1. When an object is defined as a global variable , When the whole program is finished , The object will be automatically destroyed , The destructor is automatically called
# print("start")
# p = Person()
# print("over")
"""
start
The constructor was called ~~~~
over
The destructor was called ~~~~
"""
print("*" * 30)
# # 2. When an object is defined as a local variable 【 Function 】, When the function is finished executing , The object will be automatically destroyed , The destructor is automatically called
# def func():
# p = Person()
# print("start")
# func()
# print("over")
"""
start
The constructor was called ~~~~
The destructor was called ~~~~
over
"""
print("*" * 30)
# 3.del xx, When del completion of enforcement , The object will be destroyed immediately ,, The destructor is automatically called
print("start")
p = Person()
del p
print("over")
"""
start
The constructor was called ~~~~
The destructor was called ~~~~
over
"""
# Usage scenarios for destructors : Rarely used , But it can be used for program cleanup behavior , Such as : Close file , Shut down the database, etc
3. Class properties and instance properties
【 Interview questions 】 The difference between class attributes and instance attributes
a. The definition is different : Class properties are defined directly in the class , The instance property is defined in the constructor perhaps Dynamic binding
b. Different ways to visit : Class attributes can be accessed by class name or object , Instance properties can only be accessed through objects
c. The priority of access is different : When the class attribute and instance attribute have the same name , Object access , The priority access is the instance property
d. The timing in memory is different : Class properties appear in memory prior to instance properties , Class properties appear with the loading of the class , Instance properties only appear when the object is created
e. Different scenarios : If it is data shared by all objects , Is defined as a class attribute , If the data is unique to each object , Is defined as the instance attribute
class Person():
# Class properties 【 Class field 】
num = 66
test = "abc"
def __init__(self,name,age):
# Instance attributes 【 Object properties 、 Object field 】
self.name = name
self.age = age
self.test = "hello"
p = Person('aaa',10)
# Instance attributes 【 Object properties 、 Object field 】
p.score = 100
# access
# Instance attributes : object . attribute
print(p.name,p.age,p.score)
# Class properties : object . attribute or Class name . attribute
print(p.num)
print(Person.num)
# priority
print(Person.test) # abc
print(p.test) # hello
del p.test
print(p.test) # abc
print("*" * 40)
p1 = Person('bbb',20)
print(p.num) # 66
print(p1.num) # 66
# Modify class properties
# Be careful 1: object . attribute = value , This syntax represents dynamically bound attributes , The attribute here represents the instance attribute
# p.num = 88
# print(Person.num) # 66
# Be careful 2: If you want to modify the value of a class property , Through Class name . attribute = value modify
Person.num = 88
print(Person.num)
print(p.num) #
print(p1.num) #
# Different scenarios : If it is data shared by all objects , Is defined as a class attribute , If the data is unique to each object , Is defined as the instance attribute
class Student():
school = " Qian Feng "
def __init__(self,name,score):
self.name = name
self.score = score
s1 = Student(" Zhang San ",100)
s2 = Student(" Li Si ",88)
print(s1.school,s2.school)
Student.school = " Wanfeng "
print(s1.school,s2.school)
s1.name = 'jack'
print(s2.name)
Two 、 encapsulation
1. Concept
Packaging in a broad sense : Function definition and class extraction , Are the embodiment of encapsulation
In a narrow sense : In object oriented programming , Some properties of a class , In use , If you don't want to be outside 【 direct 】 visit , You can encapsulate this property 【 Privatize properties that do not want to be directly accessed by the outside world private, This property can only be held by the current class , At this point, you can expose an access function to the outside world 】
The essence of encapsulation : Is the process of property privatization
Benefits of encapsulation : Improved data security , It improves the reusability of data
give an example : Insert , You don't need to worry about what the attributes do inside the class , Just care that you can pass values in , You can also get the value
2. Private property
2.1 Basic use
Public attributes 【public】: Properties that can be accessed directly from anywhere outside the class
Private property 【private】: Properties that can only be accessed directly inside the current class
# 1. Property is not privatized 【 Public attributes 】
# characteristic : Properties that can be accessed directly in the class and anywhere outside the class
class Animal1():
def __init__(self,name,age):
self.name = name
self.age = age
# Access inside the class
def show(self):
print(f" full name :{self.name}, Age :{self.age}")
a1 = Animal1(' Wangcai ',2)
# Access directly outside the class
# Get value
print(a1.name,a1.age)
a1.show()
# Modified value
a1.name = " The small white "
a1.age = 3
print(a1.name,a1.age)
a1.show()
print("*" * 50)
# 2. Privatize properties 【 Private property 】
# characteristic : Properties that can only be accessed directly inside the current class
class Animal2():
__slots__ = ("__name","__age")
def __init__(self,name,age):
# stay Python in , Add two underscores in front of the attribute name , This property is called a private property
self.__name = name
self.__age = age
def show(self):
print(f" full name :{self.__name}, Age :{self.__age}")
a2 = Animal2(' Wangcai ',2)
# Get value
a2.show()
# print(a2.name,a2.age)
# print(a2.__name,a2.__age)
"""
working principle :
Once an attribute is privatized , Will exist in memory in another form , General format :_ Class name __ Property name
Maybe in different versions , Under different operating systems , Private properties may exist in different forms , cannot access
Now that the properties have been privatized , I don't want to be visited by the outside world
"""
# Not recommended
# print(a2._Animal2__name)
# print(a2._Animal2__age)
print("*" * 30)
# 3. Functions provided for external access 【 Use less 】
# a.
class Animal3():
__slots__ = ("__name","__age")
def __init__(self,name,age):
self.__name = name
self.__age = age
def show(self):
print(f" full name :{self.__name}, Age :{self.__age}")
# Get value
def get_name(self):
return self.__name
# Modified value
def set_name(self,name):
self.__name = name
def get_age(self):
return self.__age
def set_age(self,age):
if age < 0:
age = -age
self.__age = age
a3 = Animal3(' Wangcai ',2)
print(a3.get_name()) # a3.name
a3.set_name(" The small white ") # a3.name = " The small white "
print(a3.get_name())
print(a3.get_age())
a3.set_age(-18)
print(a3.get_age())
print("*" * 30)
# b. stay Python in , Functions that provide access to the outside of the class through decorators
# @property: The function to be decorated can be used as an attribute , The function is to obtain the value , Format : object . Function name Means to get the return value of the function
# @xxx.setter: The function to be decorated can be used as an attribute , The function is to assign values to attributes , Format : object . Function name = value
class Animal3():
__slots__ = ("__name","__age")
def __init__(self,name,age):
self.__name = name
self.__age = age
def show(self):
print(f" full name :{self.__name}, Age :{self.__age}")
# By @property The decorated function is used to get the attribute value , amount to get_age()
@property
def name(self):
return self.__name
# By @xxx.setter Decorated functions are used to set values for attributes , amount to set_age(),xxx Said by @property Decorated function name
@name.setter
def name(self,name):
self.__name = name
@property
def age(self):
return self.__age
@age.setter
def age(self,age):
if age < 0:
age = -age
self.__age = age
a3 = Animal3(' Wangcai ',2)
print(a3.name) # Called by @property Functions of decoration , Get the return of this function
a3.name = " tearful " # Called by @name.setter Functions of decoration , Assign a value to a property
print(a3.name)
print(a3.age)
a3.age = 4
print(a3.age)
# Be careful :@property Can be used alone , You can decorate any function ,@xxx.setter Not to be used alone
2.2 Different forms of attributes
"""
【 Interview questions 】 Explain the meaning of the following different forms of variables in the class
a: General attribute , Also known as public properties , Outside the class, you can directly access ****
_a: Outside the class, you can directly access , But not recommended , Easily confused with private attributes
__a: Private property , Can only be accessed directly inside a class . Classes can be accessed through exposed functions *****
__a__: Outside the class, you can directly access , But not recommended , Because system properties and magic methods are named in this form ,
Such as :__slots__ __init__ __new__ __del__,__name__,__add__,__sub__,__mul__ etc.
"""
class Person():
def __init__(self,name,age,weight,score):
self.name = name
self._age = age
self.__weight = weight
self.__score__ = score
p = Person(" Xiao Ming ",10,150,80)
print(p.name)
print(p._age)
print(p.__score__)
3. Private functions
# 1.
# class Person():
# # Public functions
# def func1(self):
# print("func~~~111")
# p = Person()
# p.func1()
# 2.
class Person():
# Public functions
def func1(self):
print("func~~~222")
self.__show()
# Private functions
def __show(self):
print("showing")
p = Person()
p.func1()
# p.__show()
"""
Be careful :
a. If a function needs to be privatized , You can define an open function in the class , Call the private function in the public function
b. The instance functions in the class call each other , grammar :self. Function name ( Shape parameter )
c. If the encapsulated function only wants to be used inside the class , The outside of the class does not want to be accessed
"""
Role of encapsulation :
a. Improved data security
b. It improves the reusability of data