zoukankan      html  css  js  c++  java
  • 面向对象进阶

    反射

    实现通过字符串取出同名的变量

    反射对象中的属性和方法

    class Person:
        city = 'zhengzhou'
        def show_info(self):
            print('info---')
        @classmethod
        def show_city(cls):
            print('city---')
    # 使用类调用属性
    if hasattr(Person,'city'):  #先判断有没有,有再获取,防止没有该属性而报错
        res = getattr(Person,'city')
        print(res)
    # 使用类调用方法
    if hasattr(Person,'show_city'): #先判断有没有,有再获取,防止没有该方法而报错
        res2 = getattr(Person,'show_city')  #得到一个方法地址
        res2()  #调用方法
    
    # 对象调用方法
    jcc = Person()
    if hasattr(jcc,'show_info'):
        fun = getattr(jcc,'show_info')
        fun()
    反射类属性方法和对象属性方法

    反射内置模块

    import time
    inp = input('>>>')
    t1 = getattr(time,inp)
    print(t1())
    反射time模块中的方法

    反射本模块中的变量和方法

    import sys
    year = 2018
    def jcc():
        print('jcc')
    print(sys.modules['__main__'])  #得到本模块
    getattr(sys.modules['__main__'],'year')     #反射得到变量
    fun = getattr(sys.modules['__main__'],'jcc')
    fun()
    反射本模块的变量和方法

    反射有参数的函数

    class Person():
        @staticmethod
        def getinfo(name,age):
            print('%s,%s'%(name,age))
    fun = getattr(Person,'getinfo')
    fun('jcc','18')     #参数直接传
    有参数的函数的反射

     面向对象相关的几个内置函数

    __str__    在调用str()或者print函数的时候调用,如果__str__没有被定义,那么就会使用__repr__来代替输出
    __repr__    在调用repr()的时候调用


    注意:  这俩方法的返回值必须是字符串,否则抛出异常
    __del__    析构方法,由解释器在进行垃圾回收时自动触发执行

    item系列

    可以使用操作字典的方式来操作类属性

    __getitem__

    __setitem__

    __delitem__

    __delattr__

    class Person():
        def __init__(self,name):
            self.name = name
        def __getitem__(self, item):
            print('getitem')
            return self.__dict__[item]
        def __setitem__(self, key, value):
            print('setitem')
            self.__dict__[key] = value
        def __delitem__(self, key):
            print('delitem')
            self.__dict__.pop(key)
        def __delattr__(self, item):
            print('delattr')
            self.__dict__.pop(item)
    
    
    p = Person('jcc')
    print(p['name'])    #自动调用__getitem__
    p['age'] = 16       #自动调用__setitem__
    del p.age           #自定调用__delattr__
    del p['age']        #自动调用__delitem__
    示例代码

    __new__

    创建一个对象时调用,在__init__之前调用

    class Person():
        def __init__(self,name):
            print('__init__')
            self.name = name
        def __new__(cls, *args, **kwargs):
            print('__new__')
            return object.__new__(cls)
    p = Person('jcc')   #先自动调用__new__,再自动调用__init__
    
    利用__new__方法 生成一个单例模式
    class Person():
        def __init__(self,name):
            self.name = name
        def __new__(cls, *args, **kwargs):
            if not hasattr(cls,'instance'):
                cls.instance = object.__new__(cls)
            return cls.instance
    p1 = Person('jcc')
    p2 = Person('dudu')
    print(p1 ==p2)
    示例代码

    __call__

    class Person():
        def __init__(self,name):
            self.name = name
        def __new__(cls, *args, **kwargs):
            print('__new__')
            return object.__new__(cls)
        def __call__(self, *args, **kwargs):
            print('__call__')
    p = Person('jcc')   #自动调用__new__方法
    p()     #自动调用__call__方法
    call

    __eq__

    __hash__

    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
        def __eq__(self,obj):
            print('__eq__')
            if  self.a == obj.a and self.b == obj.b:
                return True
    a = A()
    b = A()
    print(a == b)   #自动调用__eq__方法
    __hash__
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __hash__(self):
            print('__hash__')
            return hash(str(self.a)+str(self.b))
    a = A()
    print(hash(a))      #自动调用__hash__方法
    eq
  • 相关阅读:
    反向代理实例
    nginx常用命令和配置
    nginx的安装
    Can Live View boot up images acquired from 64bit OS evidence?
    What is the behavior of lnk files?
    EnCase v7 search hits in compound files?
    How to search compound files
    iOS 8.3 JB ready
    Sunglasses
    现代福尔摩斯
  • 原文地址:https://www.cnblogs.com/jiangchengcheng/p/9629556.html
Copyright © 2011-2022 走看看