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

    反射(重点)

      hasattr,getsttr,setattr,delattr,其中(hasattr,getsttr成对出现,也是最重要的),(,setattr,delattr了解就行,没那么重要)

            hasttr可以调用类中的@classmethod, @staticmethod方法,也可以调用类的实例化对象

    class A:
        line = [1,2,3]
        def func(self):
            print('666')
        @classmethod
        def eat(cls):
            print('吃粑粑')
    a=A()
    if hasattr(a,'line'):
        print(getattr(a,'line'))         #[1, 2, 3]
    ret = getattr(a,'func')
    ret()                                #666
    if hasattr(A,'eat'):
        rep = getattr(A,'eat')
        rep()                            #吃粑粑

      反射当前模块

    import sys
    def func():
        print('666')
    year = 2019
    print(getattr(sys.modules[__name__],'year'))         #2019
    getattr(sys.modules['__main__'],'func')()                #666

       导入其他模块,利用反射查找该模块是否存在某个方法

    import time
    
    print(time.strftime('%Y-%m-%d %X'))
    time.sleep(1)
    print(getattr(time,'strftime')('%Y-%m-%d %X'))

      __str__和__repr__

      自我感觉__str__和 __repr__没多大的区别,只是__repr__ 在python解析器里面不用输出就可以打印返回值

    class Student:
        def __init__(self,name,salary):
            self.name = name
            self.salaey =salary
        def __str__(self):
            return self.name
    
    a=Student('小明',6000)
    print(a)           #小明

      __repr__

    class Student:
        def __init__(self,name,salary):
            self.name = name
            self.salary =salary
        def __repr__(self):
            return self.name
    a=Student('小明','6000')
    print(a)                  #小明

       剩余的可以查看Q1mi博客(地址:http://www.cnblogs.com/Eva-J/articles/7351812.html)

  • 相关阅读:
    Go语言指针
    程序员 需要掌握得600个英语单词
    Go语言管道
    Go语言容器
    Go语言切片
    Go语言类型转换
    Go语言数组
    LR静态存储/动态存储/指针变量脚本说明
    MQ报错2009/2085解决方法
    Windows性能监控监视器(perfmon使用)
  • 原文地址:https://www.cnblogs.com/wm0217/p/10911628.html
Copyright © 2011-2022 走看看