zoukankan      html  css  js  c++  java
  • Day 5-6 反射和内置方法之item系列

    python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)

     1 #!_*_ coding:utf-8 _*_
     2 
     3 class People:
     4     def __init__(self, name, age):
     5         self.name = name
     6         self.age = age
     7 
     8     def talk(self):
     9         print("%s is talking" % self.name)
    10 
    11 
    12 p = People("Jack",20)
    13 
    14 print(hasattr(p,"name"))  # 判断对象p中有没有name属性 p.__dict__["name"]
    15 print(p.__dict__["name"])
    16 
    17 print(getattr(p, "age", None))   # 获取对象中age的值
    18 print(getattr(p, "age11", None))  # 不存在会返回None
    19 
    20 setattr(p,"sex", "")  #可以在修改和新增
    21 print(p.sex)
    22 
    23 delattr(p, 'age')
    24 print(p.__dict__)  # {'name': 'Jack', 'sex': '男'} age已经被删除了

    反射的应用:

    # #!_*_ coding:utf-8 _*_
    #
    # class People:
    #     def __init__(self, name, age):
    #         self.name = name
    #         self.age = age
    #
    #     def talk(self):
    #         print("%s is talking" % self.name)
    #
    #
    # p = People("Jack",20)
    #
    # print(hasattr(p,"name"))  # 判断对象p中有没有name属性 p.__dict__["name"]
    # print(p.__dict__["name"])
    #
    # print(getattr(p, "age", None))   # 获取对象中age的值
    # print(getattr(p, "age11", None))  # 不存在会返回None
    #
    # setattr(p,"sex", "男")  #可以在修改和新增
    # print(p.sex)
    #
    # delattr(p, 'age')
    # print(p.__dict__)  # {'name': 'Jack', 'sex': '男'} age已经被删除了
    #
    #
    # 反射的应用.模拟用户输入一些命令,让程序去调用这些命令.
    # class Service:
    #     def run(self):
    #         while True:
    #             # inp = input(">>>>:").strip() #正常输入一个命令,判断在类中有没有这样一个属性方法.如果有就去执行.
    #             inp = input(">>>>:").strip()
    #             if hasattr(self,inp):
    #                 func = getattr(self,inp)
    #                 func()
    #             elif inp == "b":
    #                 break
    #             else:
    #                 print("input error")
    #
    #
    #
    #     def get(self):
    #         print("get.....")
    #
    #
    #     def put(self):
    #         print("put.....")
    class Service:
        def run(self):
            while True:
                # inp = input(">>>>:").strip() #正常输入一个命令,判断在类中有没有这样一个属性方法.如果有就去执行.
                inp = input(">>>>:").strip()
                cmds = inp.split()  # 用户传入get b.txt 这样的命令,进行分割
                print(cmds)
                if hasattr(self,cmds[0]):
                    func = getattr(self,cmds[0])
                    func(cmds)
                elif inp == "b":
                    break
                else:
                    print("input error")
    
    
        def get(self,cmds):
            print("get.....", cmds)
    
    
        def put(self,cmds):
            print("put.....",cmds)
    
    
    obj = Service()
    
    obj.run()

    __setitem__,__getitem,__delitem__

     1 class Foo:
     2 
     3     def __init__(self, name, age):
     4         self.name = name
     5         self.age = age
     6 
     7     def __getitem__(self, item):
     8         return self.__dict__.get(item)
     9 
    10     def __setitem__(self, key, value):
    11         self.__dict__[key] = value   # 新增或者修改对象的字典.
    12 
    13 
    14     def __delitem__(self, key):
    15         # self.__dict__.pop(key)   # 删除相应的键值对
    16         del self.__dict__[key]     # 两种删除方法.
    17 
    18 
    19 
    20 obj = Foo("Jack",19)
    21 # 查看.如果我们使用["str"]的方式来取值时,总是会调用__getitem__方法.
    22 print(obj["age"])  # 19
    23 print(obj["name"]) # Jack
    24 # 新增或修改.调用的是___setitem__的方法.
    25 obj["sex"] = ""
    26 obj["age"] = 20
    27 print(obj.__dict__)  # {'name': 'Jack', 'age': 20, 'sex': '男'}
    28 print(obj["sex"])     #
    29 # 删除.调用__delitem__方法
    30 del obj["age"]
    31 print(obj.__dict__)  # 删除后,__dict__中已经没有age这个键值对了.{'name': 'Jack', 'sex': '男'}

     __str__方法

    作用:使用print方法打印对象时,可以通过__str__方法,把内容显示出来.

     1 # __str__方法
     2 
     3 class People:
     4 
     5     def __init__(self, name, age):
     6         self.name = name
     7         self.age = age
     8 
     9     def __str__(self):  #__str__方法,会在print(obj)对象的时候,会被调用.返回的必须是一个字符串形式的内容.否则报错.
    10         data = {
    11             "name":self.name,
    12             "age":self.age
    13 
    14         }
    15 
    16         return str(data)  # 把字典转成字符串格式.否则报错.
    17 
    18 
    19 
    20 p1 = People("Jack", 19)
    21 print(p1)       # 调用的是__str__方法.等价于print(p1.__str__())

    __del__方法

    作用:在python程序运行结束之前,把调用的操作系统的资源回收掉.(清空)

     1 class Open:
     2 
     3     def __init__(self,filename):
     4         self.filename = filename
     5         print("Open file.....")
     6 
     7     def __del__(self):
     8         print("系统回收资源中.....")
     9 
    10 
    11 f = Open("1.txt")
    12 
    13 
    14 print("pro is end")  # 程序执行到这里的时候,接下来会执行__del__方法,回收掉py调用的操作系统的资源.

     __new__方法:

    class People(object):
    
        def __init__(self):
            print("__init__")
    
    
        def __new__(cls, *args, **kwargs):  #__new__是创建实例的方法,而__init__则是创建后,调用的方法.
            print("__new__")
            return object.__new__(cls, *args, **kwargs)
    
    
    
    People()
    #__new__
    #__init__
  • 相关阅读:
    Django笔记:上下文处理器和中间件
    Django笔记:Cookie和Session
    redhat 7.4从openssh7.6离线升级openssh8.4p1解决方法
    “应用程序无法正常启动(0xc000007)”处理办法
    "安装VMware Tools"显示灰色的解决办法
    redis 根据模板批量生成使用不同端口的配置文件并运行运行服务
    扩展 docker 管理命令
    shell getopt 讲解
    编写 Redis 测试 shell 脚本
    自定义 shell 软件安装脚本
  • 原文地址:https://www.cnblogs.com/lovepy3/p/8987841.html
Copyright © 2011-2022 走看看