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

[Python] class method, property class attribute, singleton mode

編輯:Python

One 、 Class method

Example method ( Default ): python The interpreter automatically converts the object / Instance incoming method .
Class method (@classmethod):python The interpreter will automatically pass the class into the method .
Static methods ( @staticmethod):python The interpreter does not automatically pass in any parameters

""" Related source code :from datetime import datetime """
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
# Example method , python The interpreter automatically converts the object / Instance incoming method .
def get_age(self):
print('self:', self)
return self.age
# Class method :python The interpreter will automatically pass the class into the method .
@classmethod
def get_cls(cls):
print('cls:', cls)
# Static methods :python The interpreter does not automatically pass in any parameters 
@staticmethod
def get_info():
print("static method Information ")
if __name__ == '__main__':
s = Student(' Zhang San ', 18)
s.get_age()
s.get_cls()
s.get_info()
# result 
self: <__main__.Student object at 0x00000212733F6530> # Incoming sample 
cls: <class '__main__.Student'> # Pass in the class name 
static method Information # Nothing is introduced 

Two 、property Class properties

Class methods can be defined as class attributes , No need to add when calling (), It is similar to calling a variable , I don't realize that I called a function .

Example

Class attribute application requirements : For the list page showing computer hosts in jingdong mall , It is not possible to display everything in the database on the page every request , Instead, it is displayed locally through the function of paging , So when requesting data from the database, the specified fetch to be displayed is obtained from the m To the first article n All data of bar The paging capabilities include :
1、 Based on the current page and the total number of data bars requested by the user m and n
2、 according to m and n Go to the database and request data

from datetime import datetime
""" class Page(object): """
[user1, user2, user3......user100]
page=2, per_page=10
first page : start=0 end=10
The second page : start=10 end=20
The third page : start=20 end=30
....
The first page page : start=(page-1)*per_page end=page*per_page
"""
def __init__(self, page, per_page=10):
self.page = page
self.per_page = per_page
# Class properties : The process of turning a class method into a class attribute .
@property
def start(self):
return (self.page-1) * self.per_page
@property
def end(self):
return self.page * self.per_page
if __name__ == '__main__':
goods = ['good'+str(i+1) for i in range(100)]
page = Page(page=10, per_page=3)
print(goods[page.start:page.end]) # Because of class attributes page.start() It can be changed to page.start

3、 ... and 、 The singleton pattern

1、 Basic knowledge
A class can only build a design pattern of one object
The address of the singleton mode is different

class People():
pass
p1 = People()
p2 = People()
print(p1, p2)
print(p1 is p2) # Determine whether it is in singleton mode (p1 and p2 Is the memory address the same )
# result 
<__main__.People object at 0x000002272C502560> <__main__.People object at 0x000002272C502650>
False

2、 Based on the instantiation of decorators

1、 To ensure singleton mode , Judge whether the class has been instantiated as an object
2、 If there are objects , Directly return the existing object
3、 If not, instantiate the object , And store classes and objects in the dictionary , Finally return the object
from functools import wraps
def singleton(cls):
# Store class and object information through a dictionary {"Class":"object"}
instances = {
}
@wraps(cls)
def wrapper(*args, **kwargs):
# To ensure singleton mode , Judge whether the class has been instantiated as an object 
# 1. If there are objects , Directly return the existing object 
# 2. If not, instantiate the object , And store classes and objects in the dictionary , Finally return the object 
if instances.get(cls):
return instances.get(cls)
object = cls(*args, **kwargs)
instances[cls] = object
return object
return wrapper
@singleton
class People(object):
pass
class People():
pass
p1 = People()
p2 = People()
print(p1, p2)
print(p1 is p2) # Determine whether it is in singleton mode (p1 and p2 Is the memory address the same )
# result 
<__main__.People object at 0x0000020350F37FD0> <__main__.People object at 0x0000020350F37E80>
False

3、 be based on new Method implementation of the singleton model

1、new Method is a creation · The process
2、 Class methods execute before creating objects
3、 stay new Method after execution , Encapsulate attributes and objects
class People(object):
_instance = None
def __new__(cls, *args, **kwargs):
""" What to do before creating the object """
if cls._instance is None:
cls._instance = object.__new__(cls)
return cls._instance
def __init__(self):
""" stay new Method after execution , Encapsulate attributes and objects """
print(" Executing constructor init......")
p1 = People()
p2 = People()
print(p1, p2)

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