zoukankan      html  css  js  c++  java
  • python------面向对象

    反射--实例

    class Dog(object):
    
        def __init__(self,name):
            self.name = name
    
        def eat(self,food):
            print("%s is eating...%s"%(self.name,food))
    
    def bulk(self):
    
        print("%s is yelling..."%self.name)
    
    
    d  = Dog("小光")
    #根据用户输入调用方法
    choice = input(">>:").strip()
    # hasattr(obj,name_str) 根据一个对象obj里是否有相应的name_str字符串的方法
    #getattr(obj,name_str) 根据字符串去获取obj对象里的对应的方法内存地址
    if hasattr(d,choice):
        func = getattr(d,choice)
        func("")
    else:
    
        setattr(d,choice,bulk)
        func = getattr(d,choice)
        func(d)
        #d.talk(d)
    View Code

    继承---实例

    #class People : 经典类
    class People(object):#新式类
        def __init__(self,name,age,address):
            self.name = name
            self.age = age
            #私有化变量加俩个下划线
            self.__address = address
    
    
        def sleep(self):
                print("%s is sleeping"%self.name)
    
    class MakeFriend(object):
    
        def make_friends(self,obj):
            print("%s is makeing friends with %s"%(self.name,obj.name))
    
    #多继承方法
    class Man(People,MakeFriend):
    
        #构造函数重构,在子类中重写init方法,添加新属性,并且不影响父类
        def __init__(self,name,age,address,money):
            #俩种方法格式重构父类,推荐使用super的方法
            #People.__init__(self,name,age,address)
            super(Man,self).__init__(name,age,address) #新式类写法。
            self.money = money
        #重写父类方法,添加新方法
        def sleep(self):
            People.sleep(self)
            print("man is sleeping")
    
    m1 = Man("张三",15,"中国",11)
    w2 = Man("李四",16,"中国",1)
    m1.make_friends(w2)
    View Code
  • 相关阅读:
    bzoj3653: 谈笑风生
    bzoj1858: [Scoi2010]序列操作
    bzoj1857: [Scoi2010]传送带
    bzoj1856: [Scoi2010]字符串
    bzoj1855: [Scoi2010]股票交易
    bzoj1854: [Scoi2010]游戏
    bzoj1853: [Scoi2010]幸运数字
    斜堆,非旋转treap,替罪羊树
    NOI2003 文本编辑器
    A_star poj2449 k短路
  • 原文地址:https://www.cnblogs.com/xiangrikuidebuluo/p/9554490.html
Copyright © 2011-2022 走看看