zoukankan      html  css  js  c++  java
  • Python学习week7_映射

    映射:通过用户输入的字符串调用对象的属性和方法。

    调用时使用对象真实的方法名和属性名,***attr()的参数使用的是用户输入的字符串,由此完成用户输入的字符串和对象实际属性和方法的连接。

    hasattr(obj,name_str)  判断对象obj里面是否有对应的name_str字符串的方法;

    getattr(obj,name_str)  根据字符串去获取obj对象里的对应的方法的内存地址;

    class Person(object):
        def __init__(self,name):
            self.name=name
        def eat(self,food):
            print('%s is eating '%self.name,food)       #注意此处的用法
    
    p1=Person('刚田武')
    choice=input('please input:').strip()
    if hasattr(p1,choice):
        func=getattr(p1,choice)
        func('包子')
    运行后输入eat,输出为:
    刚田武 is eating  包子
    如果输入的是name,程序报错,func被赋值p1.name,是属性值,不能被调用

     setattr(obj,'name_str',z)  相当于obj.name_str=z

    用来设置属性值时:

    class Person(object):
        def __init__(self,name):
            self.name=name
        def eat(self,food):
            print('%s is eating '%self.name,food)       #注意此处的用法
    def laugh(self):
        print('%s is laughing'%self.name)
    p1=Person('刚田武')
    choice=input('please input:').strip()
    if hasattr(p1,choice):
        setattr(p1,choice,'胖虎')
    print(p1.name)
    运行后,输入name,输出为:
    胖虎
    

     用来设置成方法时:

    class Person(object):
        def __init__(self,name):
            self.name=name
        def eat(self,food):
            print('%s is eating '%self.name,food)       #注意此处的用法
    def laugh(self):
        print('%s is laughing'%self.name)
    p1=Person('刚田武')
    choice=input('please input:').strip()
    if hasattr(p1,choice):
        setattr(p1,choice,'胖虎')
    else:
        setattr(p1,choice,laugh)
        p1.talk(p1)
    
    运行,只有当输入talk时,程序正常运行,输出为:
    刚田武 is laughing
    
    把:
    else:
        setattr(p1,choice,laugh)
        p1.talk(p1)
    修改成:
    else:
        setattr(p1,choice,laugh)
        func =getattr(p1,choice)
        func(p1)
    输入任意,都可以执行laugh()方法
    

    delattr(obj,name_str)  删除obj.name_str属性

  • 相关阅读:
    利用相关的Aware接口
    java 值传递和引用传递。
    权限控制框架Spring Security 和Shiro 的总结
    优秀代码养成
    Servlet 基础知识
    leetcode 501. Find Mode in Binary Search Tree
    leetcode 530. Minimum Absolute Difference in BST
    leetcode 543. Diameter of Binary Tree
    leetcode 551. Student Attendance Record I
    leetcode 563. Binary Tree Tilt
  • 原文地址:https://www.cnblogs.com/zhhy236400/p/9786533.html
Copyright © 2011-2022 走看看