程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python notes 19- Operator Overloading & polymorphism & static method and class method & singleton design pattern

編輯:Python

One 、 Operator overloading 【 Focus on mastering 】

"""
【 Interview questions 】 Briefly describe the difference between function rewriting and function overloading
Function rewriting :override, On the premise of inheritance , If the function in the parent class is re implemented in the child class
Operator overloading / function overloading :overload, For custom classes , Objects created through this class , If some operations are not supported ,
Such as :+ - * / > < >= <= == != etc. , You can implement the functions corresponding to these operators in this class
"""
# Functions defined in the system , If there are two underscores before and after the name , Then this kind of function is called magic function / Magic methods / Double underline method
# 1.dir( object ): Get the function or property related to the specified object
# print(dir("abc"))
# print(dir(10))
# print(dir([1,3]))
# print(dir((1,3)))
# print(dir({'a':10}))
# 2.+ - * /
"""
__add__() +
__sub__() -
__mul__() *
__mod__() %
__divmod__ /
"""
# __add__() For example
# a
print(12 + 10)
print(12 + 45.6)
print(34.5 + 9.7)
print('abc' + 'def')
print('abc'.__add__("def"))
print([1,2] + [4,6])
print([1,2].__add__([4,6]))
print((1,2) + (3,6))
# print({'a':10} + {'b':20})
print("*" * 50)
# b.
class Person():
def __init__(self,age):
self.age = age
# heavy load
def __add__(self, other):
# self and other Represents the two objects involved in the operation
# According to the actual situation , Two objects cannot be added directly , You can add the attributes of two objects
return Person(self.age + other.age)
# rewrite
def __str__(self):
return str(self.age)
__repr__ = __str__
p1 = Person(10)
p2 = Person(5)
# problem :Person + Person = int---->Person + Person = Person
print(p1 + p2)
print(p1.__add__(p2))
"""
working principle :
p1 + p2----》p1.__add__(p2)----》Person(self.age + other.age)
print(p1 + p2)----》print(Person(self.age + other.age))---》 Automatically call __str__
"""
# 3. > < >= <= == !=
"""
__eq__() equal,==
__ge__() greater equal >=
__gt__() greater than >
__le__() less equal <=
__lt__() less than <
__ne__() not equal !=
"""
class Person():
def __init__(self,age):
self.age = age
# Custom comparison rules
def __gt__(self, other):
# self and other Are the two objects involved in the comparison
# In general , Combined with actual use , What is involved in the comparison is the same kind of attribute of the object
# if self.age > other.age:
# return True
# return False
# return True if self.age > other.age else False
return self.age > other.age
p1 = Person(10)
p2 = Person(5)
print(p1 > p2) # True

Two 、 polymorphic

Many forms of a thing , give an example : There are many kinds of animals

It is not certain what type it is when it is defined , Which method to call , Only the runtime can determine which is called

Be careful : Inheritance is the premise of polymorphism

# polymorphic : Must be under the premise of inheritance
# 1. Many forms of a thing 【 Multiple data types of an object 】
class Animal(object):
pass
class Cat(Animal):
pass
class SmallCat(Cat):
pass
c = SmallCat()
# isinstance( object , type ): Check whether an object is a specified data type
print(isinstance(c,SmallCat))
print(isinstance(c,Cat))
print(isinstance(c,Animal))
print(isinstance(c,object))
a = Animal()
print(isinstance(a,Animal))
print(isinstance(a,Cat))
# 2. It is not certain what type it is when it is defined , Which method to call , Only the runtime can determine which is called
class Animal(object):
def show(self):
print("Animal~~~~~~~show")
class Cat(Animal):
def show(self):
print("Cat~~~~~~~show")
class SmallCat(Cat):
def show(self):
print("SmallCat~~~~~~~show")
def func(a):
a.show()
c = SmallCat()
func(c)
c1 = Cat()
func(c1)

3、 ... and 、 other

1. Object's built-in properties

# 1.__slots__: Restrict dynamic binding of object properties ****
class Person():
__slots__ = ("name",)
# 2.__doc__: Represents the description information of the class , Get the document comments in the class
class Check(object):
"""
function : Realize data verification
"""
def show(self):
pass
print(Check.__doc__)
# 3.__dict__: Get class or object information , Include properties and methods ******
class Person(object):
# Class properties
place = " The earth "
# Limiting attributes
__slots__ = ("name",)
# Constructors
def __init__(self,name):
# Instance attributes
self.name = name
# Examples of function
def show(self):
pass
# Class function
@classmethod
def func1(cls):
pass
# Static functions
@staticmethod
def func2():
pass
def __str__(self):
return self.name
__repr__ = __str__
# Class name .__dict__: You can get the class attributes in the class , Instance attributes , Constructors , Examples of function . Class function , Static functions
print(Person.__dict__)
print(list.__dict__) # dir()
# 4.__module__: Get which module the current object is in , Be similar to __name__
p = Person('aaa')
print(p.__module__)
print(__name__) # if __name__ == "__main__":
# 5.__class__: Be similar to type(xxx), Get the type of an object
print(p.__class__)
print(type(p))

2. Object's built-in functions

# 1.id(): Get the address of an object in memory
# Compare the addresses of two objects
a = 45
b = 46
print(id(a) == id(b))
print(a is b)
# 2.type(): Get the data type of an object
print(type("fajgh"))
# Compare the types of variables *****
print(type("abc") == str)
print(type("123") == type(123))
print(type(type(123))) # <class 'type'>
# Type of custom class , Format :<class '__main__. Class name '>
class Person(object):
pass
p = Person()
print(type(p))
# With the help of types modular , You can determine the type of function
import types
print(type(lambda x:x ** 2) == types.LambdaType)
print(type((i for i in range(5))) == types.GeneratorType)
# 3.isinstance(): Determine whether an object is a specified data type ******
print(type("abc") == str)
print(isinstance("abc",str))
# 4.dir() : View information about an object ******
print(dir(34))
# 5.issubclass(): Determine whether there is an inheritance relationship between two classes
class Animal(object):
def __init__(self,name):
self.name = name
def eat(self):
print("eating")
class Cat(Animal):
pass
print(issubclass(Cat,Animal))
print(issubclass(Cat,object))

3. Class methods and static methods 【 Focus on mastering 】

【 Interview questions 】 Briefly describe the instance function , The difference between class functions and static functions

a. Different definitions : By @classmethod Decorated functions represent class functions , By @staticmethod Decorated functions represent static functions , The instance function has no decorator specified

b. Parameter list is different : The first argument to the instance function is self, Represents the current object , The first argument to a class function is cls, Represents the current class , Static functions do not require parameters

c. Different ways of calling : Both class functions and static functions can be called by class name or object , however , Instance functions can only be called through objects

d. Different scenarios : If you want to encapsulate a tool class , Try to use class functions or static functions , In actual project development , Many instance functions are used , If you need to create an object in a function in a class , This function is generally defined as a class function

class Person():
# Class properties
place = " The earth "
# Constructors
def __init__(self,name,age):
# Instance attributes
self.name = name
self.age = age
# Examples of function
# self: Represents the current object
def show(self,sth):
print("showing",sth,self.name,self.age)
# Class function
# cls:class Abbreviation , Represents the current class , Use cls It is equivalent to using Person
@classmethod
def func(cls,num1,num2):
print('func~~~~',num1,num2)
# demand : Call instance functions in class functions
# First step : Create objects
c = cls(100,200) # Equivalent to Person(xx,xx)
# The second step : call
c.show(465)
# Static functions
@staticmethod
def check(a,b,c):
print('check~~~',a,b,c)
Person.func(12,45)
# Person.check(3,6,7)
#
# p = Person('aaa',10)
# p.show('apple')
# p.func(34,7)
# p.check(243,6,8)
# application : Define a tool class , Which can add, subtract, multiply and divide two numbers
class Math():
@staticmethod
def add(num1,num2):
return num1 + num2
@staticmethod
def sub(num1, num2):
return num1 - num2
@staticmethod
def mul(num1, num2):
return num1 * num2
@staticmethod
def div(num1, num2):
return num1 / num2
print(Math.add(34,10))

Four 、 Singleton design pattern 【 Focus on mastering 】

1. Concept

What is design pattern ?

 Design pattern is a summary 、 Optimization of the , Reusable solutions to some of the programming problems we often encounter
The design pattern is more advanced , It's a method template that must be implemented in a specific situation . Design patterns do not bind specific programming languages
23 Design patterns , One of the most commonly used is the singleton design pattern , Factory design mode , The proxy pattern , Decorator mode and so on

What is the singleton design pattern ?

 Single case : A single instance 【 Single object 】, A class can only create one object
During the operation of the program , Make sure there is only one instance of a class 【 object 】, No matter which module gets the object of this class , All the obtained objects are the same object . This class has a static method , Provide this example to the whole project , for example : A country has only one President , No matter where he is

The core of the singleton design pattern : A class has and only has one instance , And this instance needs to be applied to the whole program , This class is called a singleton class

reflection : Verify that the two variables represent the same object , How to verify ?

solve : Verify address , The way :is perhaps id()

2. Application scenarios

The class corresponding to the currently used user is described in the application ———> The current user is unique to the operation of the application ——> Therefore, the object is generally designed as a singleton

The practical application : Database connection pool operation ——> Connect to the database in multiple places in the application ———> Only one connection pool is needed to connect to the database , There is no need to create a new connection pool everywhere , This is also a waste of resources ————> The solution is also a single case

3. Realization

3.1 Mode one

# Define a class , This class can only create one object , This class is called a singleton class , This implementation is called the singleton design pattern
# 1, General class : You can create countless objects
class Person1(object):
def __new__(cls, *args, **kwargs):
print("new Is called the ~~~~~")
return super().__new__(cls)
def __init__(self,name,age):
print('init Is called the ')
self.name = name
self.age = age
p1 = Person1(' Zhang San ',10)
p2 = Person1(" Li Si ",20)
print(p1 is p2) # False
print(id(p1),id(p2))
print("*" * 50)
# 2
class Person2(object):
# Define a private class property , Represents the only instance that the current class can create
__instance = None
# super().__new__(cls) But once , A new object is created ,
# So as long as super().__new__(cls) Execute only once from beginning to end , It means that there is only one object
def __new__(cls, *args, **kwargs):
print("new Is called the ~~~~~")
# Judge __instance Is it None, If it is , Will super().__new__(cls) Assign a value to __instance
# If not , Then return directly
if not cls.__instance:
print("if Execution of statements ")
cls.__instance = super().__new__(cls)
return cls.__instance
def __init__(self,name,age):
print('init Is called the ')
self.name = name
self.age = age
p1 = Person2(' Zhang San ',10) # establish
p2 = Person2(" Li Si ",20) # Return the first created object
print(p1 is p2) # True
print(id(p1),id(p2))
# reason : Every time you execute p = Person2(xx,xx), It will be carried out __init__()
print(p1.name,p2.name) # Li Si
p1.name = "aaa"
print(p1.name,p2.name) # aaa

3.2 Mode two

# 1. Decorator decorator function
def wrapper(func):
print('1111')
def inner():
print("new~~~~~~")
func() # test()
return inner
@wrapper # call wrapper()
def test():
print("testing")
test() # inner()
print("*" * 50)
# 2. Ornaments, ornaments
def wrapper(cls):
print('1111')
def inner():
print("new~~~~~~")
cls() # Test() Create objects , Constructors
return inner
@wrapper # call wrapper(Test)
class Test():
print("testing")
Test() # inner()
print("*" * 30)
# 3.
def singleton(cls): # cls--->Person1
# Definition instance, Represents the only object that the decorated class can create
instance = None
def get_instance(*args,**kwargs):
nonlocal instance
if not instance:
instance = cls(*args,**kwargs) # Create objects of decorated classes , call __init__
return instance
return get_instance
@singleton
class Person1(object):
def __init__(self,name,age):
self.name = name
self.age = age
print('init Is called the ',self.name,self.age)
p1 = Person1(' Zhang San ',10) # call get_instance function
p2 = Person1(" Li Si ",20)
print(p1 is p2) # True
print(id(p1),id(p2))
# reason : Only the first execution p = Person1(xx,xx), Will execute cls(*args,**kwargs), It will also carry out __init__()
print(p1.name,p2.name) # Zhang San
p1.name = "aaa"
print(p1.name,p2.name) # aaa

3.3 Mode three

def singleton(cls):
# Define a dictionary , Used to store decorated classes and corresponding unique objects
# key: The decorated class value: The only object that the decorated class can create
instance_dict = {}
def getinstance(*args,**kwargs):
# Judge instance_dict It's empty , Add a pair of key value pairs to the dictionary
if not instance_dict:
instance_dict[cls] = cls(*args,**kwargs)
return instance_dict[cls]
return getinstance
@singleton
class Person(object):
def __init__(self,name):
self.name = name
p1 = Person(" Zhang San ")
p2 = Person(" Li Si ")
print(p1 is p2)
print(id(p1) == id(p2))
print(p1.name,p2.name)
p1.name = "tom"
print(p1.name,p2.name)

5、 ... and 、 abstract class

"""
If a class is to extract the same attributes and methods from multiple objects , The abstract class represents extracting the same attributes or methods from a stack of classes
Abstract class is a special class , What makes it special is that it can only be used as a parent class , in other words , Can only be inherited , Can't be instantiated
The essence : Abstract classes are for inherited , It provides interfaces that subclasses can use , So in the actual development , Act as a parent
"""
# stay Python in , There is no abstract class in itself , however , Can pass abc Module simulation
import abc # abstract class
# abstract class / Parent class
class AllFile(metaclass=abc.ABCMeta):
# Define abstract methods in abstract classes , The function of this method is only to provide an interface to the subclass , You only need to implement this interface in the subclass
@abc.abstractmethod
def read(self):
pass
@abc.abstractmethod
def write(self):
pass
# def show(self):
# pass
# Subclass
class Txt(AllFile):
# rewrite
def read(self):
print("txt File reading ")
def write(self):
print("txt Writing files ")
class Excel(AllFile):
# rewrite
def read(self):
print("excel File reading ")
def write(self):
print("excel Writing files ")
class Csv(AllFile):
# rewrite
def read(self):
print("csv File reading ")
def write(self):
print("csv Writing files ")
t = Txt()
t.read()
t.write()
"""
Be careful
1. Ordinary instance functions and abstract functions can be provided in abstract classes , Object cannot be instantiated ,
however , In general , Using abstract classes , Only the abstract methods will be provided in it
2. An abstract method in an abstract class is usually just an interface , There is no need to achieve , The concrete implementation needs to be completed in the subclass
3. If a class inherits from an abstract class , But the abstract method in the abstract class is not overridden , Then the class is still an abstract class
"""

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved