Python classroom 15 Object-oriented 3 internal methods, class customization

Source: Internet
Author: User

Object-oriented 3 advanced usage binding method:

Binding methods, non-binding methods
Binding method: Object binding, class binding @ Classmethod
Non-binding @ Staticmethod

class Foo:    # 没有装饰器的函数,参数自动传入对象,和对象绑定,是对象绑定方法    def func1(self):        print(self)    # 使用classmethod装饰,自动传入类,和类绑定,是类的绑定方法。    @ classmethod    def func2(cls):        print(cls)    # 使用staticmethod装饰,不自动传入任何东西,就是普通方法    @ staticmethod    def func3():        print(‘普通工具类‘)f = Foo()f.func1()   # <__main__.Foo object at 0x000001DFFED06278>f.func2()   # <class ‘__main__.Foo‘>f.func3()   # 普通工具类
Binding object methods, binding class methods, use of non-binding methods
import dbimport time,hashlibclass People:    def __init__(self,name,age):        self.name = name        self.age = age    def info(self):        print(‘my name is %s age is %s‘%(self.name,self.age))    # 函数依赖类的传入    @classmethod    def creat_obj(cls):        obj = cls(db.name,db.age)        return obj    # 独立的工具    @staticmethod    def creat_id():        hs = hashlib.md5(str(time.time()).encode(‘utf8‘))        return hs.hexdigest()p1 = People(‘ql‘,22)p1.info()p2 = People.creat_obj()  # 使用类方法直接创建对象p2.info()id = p2.creat_id()print(id)
Property
class People:    def __init__(self,name):        self.__name = name    # 将方法伪装为属性,调用时不需要加括号。    @ property   # name = property(name)    def name(self):        return self.__name    # property 伪装成属性后,如果被赋值,将触发    @ name.setter  # name = name.setter(name) ==>name.name.__setter__()    def name(self,name):        self.__name = name        return self.__name    # property 伪装成属性后,如果被删除,将触发    @ name.deleter # 删除name 触发    def name(self):        print(‘不准删name‘)p = People(‘qianlei‘)p.name = ‘qianlei123‘print(p.name)将name 封装,看似直接调用name,其实该name 是方法,可以对查看名称进行定制。
Reflection

Reflection is called by using a string as the property name.

class People:    def __init__(self,name,age):        self.name = name        self.age = age    def info(self):        print(‘my name is %s age is %s‘%(self.name,self.age))p = People(‘qianlei‘,22)调用属性时,如果接收用户输入,将字符串作为属性名,则无法调用。想调用可以使用字典 p.__dict__[‘name‘]python 还提供了简单的解决办法print(p.name)
Reflection hasattr () GetAttr () SetAttr () delattr ()
print(hasattr(p,‘name‘))print(getattr(p,‘name‘,None)) # 第三个参数为默认返回,如果没有该属性默认返回值。print(getattr(p,‘name1‘,None))setattr(p,‘sex‘,‘male‘)print(getattr(p,‘sex‘))delattr(p,‘sex‘)print(getattr(p,‘sex‘,‘没有这个属性‘))
Reflective applications
class service():    def run(self):        while True:            res = input(‘>>>>‘).strip()            # if hasattr(self,res):  # 先判断是否有这个属性            #     func = getattr(self,res)  # 获取属性            #     func()  # 运行属性            mes_list = res.split()            if hasattr(self,mes_list[0]):                func = getattr(self,mes_list[0])                func(mes_list[1])    def get(self,mes):        print(‘get.......‘,mes)    def put(self,mes):        print(‘put.........‘,mes)s = service()s.run()
__call__ __new__ __str____call__: Converts an instance of a class into an object that can be called, instance + (), runs
class Foo:    def __call__(self, *args, **kwargs):        print(‘this is call func‘)        print(args)        print(kwargs)f = Foo()f(‘a‘, b=1)===》this is call func===》(‘a‘,)===》{‘b‘: 1}
__NEW__: Called automatically when the class is instantiated and can be customized for instantiation.
 class Foo:    def __new__(cls, *args, **kwargs):        print(‘this is new func‘)        print(args)        print(kwargs)f = Foo(‘a‘, b=1)===》this is new func===》(‘a‘,)===》{‘b‘: 1}
__STR__: Called when the instance is printed.
 class Foo:    def __str__(self):        return ‘this is str‘f = Foo()print(f)===》this is str
_ getattr___setattr__ __delattr__

Custom object Get Settings Delete Property method: _ getattr_ () _ setattr_ () _ delattr_ ()
_ getattribut_ () : The object invokes the property when it is activated, but when it throws Attributerror () it activates _ getattr_ (), which it needs to set itself.
_ getattr_ (): Object called property when no corresponding property is activated _ getattr_ ()
_ setattr_ (): object is set when the property is activated and returns the return value of the method. You can specify what is returned when the property is modified.
_ delattr_ (): The object is activated when the property is deleted, and the return value of the method is returned. You can specify what to return when you delete an attribute.

class Test():    def __init__(self,name):        self.name=name    def __getattr__(self, item):        print(‘getattr is running %s was not find ‘%item)    def __setattr__(self, key, value):        print(‘setattr is running %s is seting‘%key)        # self.key=value#这个方法会调用自己,因为方法本身就是添加属性,无限递归        self.__dict__[key]=value#设置时需要使用对象字典    def __delattr__(self, item):        print(‘delattr is running %s is del‘%item)        del self.__dict__[item]#删除对象字典元素,否则会无限递归。t=Test(‘tes‘)   #只要有属性生成或变动就会触发__setattr__print(t.erro_name)#调用不存在的属性 就会触发 __getattr__()方法t.age=20    #只要有属性生成就会触发__setattr__print(t.__dict__)del t.age#只要删除属性就会触发__delattr__print(t.__dict__)
Two-time Standard model for machining

Use inheritance to customize your own classes.
is to personalize the standard Model using inheritance,
Add your own requirements, and you can also use the functionality of the Standard Model.
For example, customizing a list, when instantiating a list, requires that the string be passed in.

class Mylist(list):    def __init__(self, strtype):        if isinstance(strtype, str):            super().append(strtype)        else:            print(‘必须传入字符串‘)# 这里必须传入字符串l = Mylist(‘123‘)print(l)# 还可以使用原来的功能。l.append(‘abc‘)print(l)
Authorized:

Use the instance of the target class to invoke the method of the target class. Equivalent to the method of authorizing the target class with an instance of the target class.
1. Add an instance of the target class to the class first
2. When you need to invoke a method in the target class, use __getattr__ () to transfer the method of the target class.
3, need to modify the target class method, then use the target class instance to give the corresponding method, and packaging modification.

import timeclass file_io():    def __init__(self,filename,mode,encoding=‘utf-8‘):        self.file=open(filename,mode,encoding=encoding)#给实例属性添加个open()实例,利用这个实例给自己添加open()中的方法。        self.mode=mode        self.encoding=encoding    # 自己定义write()方法,本质上还是调用文件对象的write()方法,给予了定制功能    def write(self,neirong):        #利用open()实例file,授权write方法,定制包装自己的write()方法。        #每次写入内容时添加时间。        t = time.strftime(‘%Y-%m-%d %X‘)        res=‘%s %s‘%(t,neirong)        return self.file.write(res)#返回文件句柄中的write()    # 调用本类没有的方法时,去对象的类中去找。。    def __getattr__(self, item):        #利用__getattr__()方法去授权对象调用open()的实例file,中的各种方法。        return getattr(self.file,item)#授权f对象使用标准文件句柄中的各种属性。f=file_io(‘test.txt‘,‘w+‘)f.file.write(‘None\n‘)#f对象调用自己的属性file,file句柄中有write()方法f.write(‘qwe\n‘)       #调用定制的write()方法 f.write(‘sdad\n‘)f.seek(0)print(f.read())#f中没有read()方法,所以触发__getattr__(),返回文件句柄本身提供的read()f.close()

Python classroom 15 Object-oriented 3 internal methods, class customization

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.