Built-in methods for Python classes

Source: Internet
Author: User

Directory

    • 1. New, Init
    • 2, str, repr
    • 3. Call
    • 4, Del
    • 5. ITER, Next
    • 6, GetItem, SetItem, Delitem
    • 7, GetAttr, SetAttr, delattr
    • 8, Getatrribute
    • 9, enter, exit
    • 10, get, set, delete, descriptor (in the study, to be supplemented)

* * (For convenience and aesthetics, omit the various built-in methods before and after the double underline) * *

1. New, Init

__new__A method is a true class construction method that is used to produce an instantiated object (an empty property). __new__the Override method controls how the object is produced.
__init__The method is the initialization method, which is responsible for initializing the attribute value on the instantiated object, which must return none, and the __new__ method must return an object. Override __init__ methods can control the initialization of an object.

# 使用new来处理单例模式class Student:    __instance = None    def __new__(cls, *args, **kwargs):        if not cls.__instance:            cls.__instance = object.__new__(cls)        return cls.__instance    def sleep(self):        print(‘sleeping...‘)stu1 = Student()stu2 = Student()print(id(stu1), id(stu2))  # 两者输出相同print(stu1 is stu2)  # True

Personal feeling, __new__ generally rarely used in ordinary business scenarios, more in the meta-class, because it can be more low-level processing object generation process. and __init__ the use of the scene more.

2, str, repr

The purpose of both is to explicitly display some of the necessary information of the object for easy viewing and debugging. __str__is called by print Default and is __repr__ called by default when it is output by the console. That is, use control to __str__ display the user, use __repr__ control to debug the display.

# 默认所有类继承object类,object类应该有一个默认的str和repr方法,打印的是对象的来源以及对应的内存地址class Student:    def __init__(self, name, age):        self.name = name        self.age = agestu = Student(‘zlw‘, 26)print(stu)  # <__main__.Student object at 0x0000016ED4BABA90>
# 自定义str来控制print的显示内容,str函数必须return一个字符串对象# 使用repr = str来偷懒控制台和print的显示一致class Student:    def __init__(self, name, age):        self.name = name        self.age = age    def __str__(self):        return f‘{self.__class__}, {self.name}, {self.age}‘        __repr__ = __str__stu = Student(‘zlw‘, 26)print(stu)  # <class ‘__main__.Student‘>, zlw, 26
3. Call

__call__Methods provide the ability for an object to be executed, like a function, and essentially, a function is an object, and a function is an object that owns a __call__ method. The __call__ object that owns the method, using the callable results that can be obtained, True can use () execution, can pass in parameters when executed, and can return a value. So we can use __call__ methods to implement instantiating objects as adorners:

  # checks the number of input parameters for a function and cannot be called if the number of arguments supplied when calling this function does not conform to a predefined definition. # simple Function Version adorner def args_num_require (require_num): Def outer (func): Def inner (*args, **kw): If Len (args)!        = Require_num:print (' function parameter number does not conform to pre-defined, cannot execute function ') return None return func (*args, **kw) return inner return Outer@args_num_require (2) def show (*args): print (' show function executed successfully! ') Show (1) # function parameter number does not conform to pre-defined, unable to execute function show (!show) # show function executed successfully (+/-) # function parameter number does not conform to predefined, cannot execute function  
# 检查一个函数的输入参数个数,# 如果调用此函数时提供的参数个数不符合预定义,则无法调用。# 实例对象版本装饰器class Checker:    def __init__(self, require_num):        self.require_num = require_num    def __call__(self, func):        self.func = func        def inner(*args, **kw):            if len(args) != self.require_num:                print(‘函数参数个数不符合预定义,无法执行函数‘)                return None            return self.func(*args, **kw)        return inner@Checker(2)def show(*args):    print(‘show函数成功执行!‘)show(1)  # 函数参数个数不符合预定义,无法执行函数show(1,2) # show函数成功执行!show(1,2,3)  # 函数参数个数不符合预定义,无法执行函数
4, Del

__del__Used to automatically call when the object's reference count is 0.
__del__Typically occurs in two places: 1, manually using Del to reduce the object reference count to 0, which is called when garbage collection is processed. 2. Called at the end of the program.
__del__Typically used to declare a resource recycle operation that needs to be processed before an object is deleted

# 手工调用del 可以将对象引用计数减一,如果减到0,将会触发垃圾回收class Student:    def __del__(self):        print(‘调用对象的del方法,此方法将会回收此对象内存地址‘)stu = Student()  # 调用对象的__del__方法回收此对象内存地址del stuprint(‘下面还有程序其他代码‘)
class Student:    def __del__(self):        print(‘调用对象的del方法,此方法将会回收此对象内存地址‘)stu = Student()  # 程序直接结束,也会调用对象的__del__方法回收地址
5. ITER, Next

These 2 methods are used to simulate a sequence of objects. Built-in types such as lists, tuples can be iterated, and file objects can be iterated to get each line of content. Overriding these two methods allows you to implement a custom iteration object.

# 定义一个指定范围的自然数类,并可以提供迭代class Num:    def __init__(self, max_num):        self.max_num = max_num        self.count = 0            def __iter__(self):        return self    def __next__(self):        if self.count < self.max_num:            self.count += 1            return self.count        else:            raise StopIteration(‘已经到达临界‘)        num = Num(10)for i in num:    print(i)  # 循环打印1---10
6, GetItem, SetItem, Delitem

Overriding this series of methods can simulate an object as a list or a dictionary, that is, a type that can be used key-value .

Class Studentmanager:li = [] dic = {} def add (self, obj): self.li.append (obj) self.dic[obj.name] = obj def __getitem__ (self, item): If Isinstance (item, int): # Gets the object return by subscript Self.li[item            ] Elif isinstance (item, slice): # Gets a string of objects by slicing start = Item.Start stop = item.stop            Return [student for student in Self.li[start:stop]] elif isinstance (item, str): # Get the object by name Return Self.dic.get (item, None) Else: # The given key type error raise TypeError (' The key type you typed is wrong! ') Class Student:manager = Studentmanager () def __init__ (self, name): Self.name = name Self.manager.add ( Self) def __str__ (self): return F ' student: {self.name} ' __repr__ = __STR__STU1 = Student (' xiaoming ') stu2 = Student (' white ') STU3 = Student (' Little red ') Stu4 = Student (' Fat Tiger ') # Use Print as List (student.manager[0]) # student: Xiao Ming Print (student.manager[-1]) # Student: Fat Tiger pri NT (Student.manager[1:3]) # [Student: Great White, student: Little Red]# as a dictionary using print (student.manager[' Fat Tiger ') # Student: Fat Tiger 
7, GetAttr, SetAttr, delattr

The method that triggers the object when it is used obj.x = y , when the object is triggered setattr del obj.x delattr .
A method is fired when attempting to access a nonexistent property of an object, by the obj.noexist getattr getattr lowest priority in the property lookup.
You can override these 3 methods to control access, setting, and deletion of object properties.
* * Special NOTE: If GetAttr is defined and there is no code (that is, only pass), all non-existent attribute values are none without error and can be handled using super (). __getattr__ () method to process * *

class Student:    def __getattr__(self, item):        print(‘访问一个不存在的属性时候触发‘)        return ‘不存在‘    def __setattr__(self, key, value):        print(‘设置一个属性值的时候触发‘)        # self.key = value  # 这样会无限循环        self.__dict__[key] = value    def __delattr__(self, item):        print(‘删除一个属性的时候触发‘)        if self.__dict__.get(item, None):            del self.__dict__[item]stu = Student()stu.name = ‘zlw‘  # 设置一个属性值的时候触发print(stu.noexit)  # 访问一个不存在的属性时候触发 , 返回‘不存在‘del stu.name  # 删除一个属性的时候触发
8, Getatrribute

This is a property access truncation , that is, when you access the property, this method truncates your access behavior and takes precedence over the code in this method, which should be the highest priority in the property lookup order.
Property Lookup Order:
Instance of the Getattribute--> instance object Dictionary--the class dictionary where the instance is located--the parent class of the instance (MRO order) dictionary--getattr--> error of the instance's class

class People:    a = 200class Student(People):    a = 100    def __init__(self, a):        self.a = a    def __getattr__(self, item):        print(‘没有找到:‘, item)    def __getattribute__(self, item):        print(‘属性访问截断器‘)        if item == ‘a‘:            return 1        return super().__getattribute__(item)stu = Student(1)print(stu.a)  # 1
9, enter, exit

The rewriting of these two methods allows us to use methods on an object with to handle pre-work preparation, as well as cleaning behavior after work.

class MySQL:    def connect(self):        print(‘启动数据库连接,申请系统资源‘)    def execute(self):        print(‘执行sql命令,操作数据‘)    def finish(self):        print(‘数据库连接关闭,清理系统资源‘)    def __enter__(self):  # with的时候触发,并赋给as变量        self.connect()        return self    def __exit__(self, exc_type, exc_val, exc_tb):  # 离开with语句块时触发        self.finish()with MySQL() as mysql:    mysql.execute()    # 结果:# 启动数据库连接,申请系统资源# 执行sql命令,操作数据# 数据库连接关闭,清理系统资源
10, get, set, delete, descriptor (in the study, to be supplemented)

Built-in methods for Python classes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.