zoukankan      html  css  js  c++  java
  • 面向对象(二十九)

    面向对象设计:

    def dog(name,type,color):
        def voice(dog):
            print("%s can wangwangwang "
            %dog["name"] )
            
        def run(dog):
            print("%s can run" %(dog["name"]))
            
        def show(dog):
            print("%s, %s, %s" %(dog["name"],dog["type"],dog["color"]))
        def init(name,type,color):
            dic={
                "name":name,
                "type" :type,
                "color" :color,
                "voice" :voice,
                "run":run,
                "show":show
            }
            return dic
        res = init(name,type,color)
        return res
        
    dog1 = dog("a","zhong","red")
    dog1["voice"](dog1)
    dog1["show"](dog1)

    面向对象编程

    实例只有变量属性,没有函数属性

    class People:
        '这是一个人类'
        def __init__(self,name,sex,age):
            print("初始化...")
            self.name = name
            self.sex = sex
            self.age = age
        def work(self):
            print("%s is working" %(self.name))
        def eating(self):
            print("%s is eating food" %(self.name))
        def show_self(self):
            print("my name is %s ,age is %d, sex is %s"
                  %(self.name,self.age,self.sex))
    
    
    p1 = People("alex","man",18)
    print(p1) # <__main__.People object at 0x000001839BD64E48>
    print(p1.__dict__) # {'sex': 'man', 'age': 18, 'name': 'alex'}
    print(People.__dict__) # {'__dict__': <attribute '__dict__' of 'People' objects>, '__module__': '__main__',
                            # '__init__': <function People.__init__ at 0x000001921A677B70>,
                            # '__doc__': None, 'eating': <function People.eating at 0x000001921ABF5C80>,
                            # 'work': <function People.work at 0x000001921ABF5B70>,
                            # 'show_self': <function People.show_self at 0x000001921ABF5BF8>, '__weakref__': <attribute '__weakref__' of 'People' objects>}
    
    print(p1.__dict__["name"]) # alex
    print(p1.name,p1.sex,p1.age)
    p1.show_self()
    People.eating(p1)

    类的属性又称静态变量,或静态数据,这些数据与他们所属的类对象绑定,不依赖于任何实例

    类的增删改查

    class People:
        '这是一个人类'
        country="China"
        def __init__(self,name,sex,age):
            print("初始化...")
            self.name = name
            self.sex = sex
            self.age = age
        def work(self):
            print("%s is working" %(self.name))
        def eating(self):
            print("%s is eating food" %(self.name))
        def show_self(self):
            print("my name is %s ,age is %d, sex is %s"
                  %(self.name,self.age,self.sex))
    
    
    p1 = People("alex","man",18)
    print(p1) # <__main__.People object at 0x000001839BD64E48>
    print(p1.__dict__) # {'sex': 'man', 'age': 18, 'name': 'alex'}
    print(People.__dict__) # {'__dict__': <attribute '__dict__' of 'People' objects>, '__module__': '__main__',
                            # '__init__': <function People.__init__ at 0x000001921A677B70>,
                            # '__doc__': None, 'eating': <function People.eating at 0x000001921ABF5C80>,
                            # 'work': <function People.work at 0x000001921ABF5B70>,
                            # 'show_self': <function People.show_self at 0x000001921ABF5BF8>, '__weakref__': <attribute '__weakref__' of 'People' objects>}
    
    print(p1.__dict__["name"]) # alex
    print(p1.name,p1.sex,p1.age)
    p1.show_self()
    People.eating(p1)
    
    # 查看类的属性
    print(People.country) # China
    print(p1.country) # China
    # 修改类的属性
    People.country = "CHINA"
    print(People.country) # CHINA
    print(p1.country) # CHINA
    # 增加
    # print(p1.color) #  white 报错
    People.color = 'white'
    print(People.color) #  white
    print(p1.color) #  white
    # 删除
    del People.color
    # print(People.color) #  white 报错

    静态属性 

    @property
    class Room:
        def __init__(self,name,width,length,height):
            self.Name = name
            self.Width = width
            self.Len = length
            self.Height = height
    
        @property
        def cal_volume(self):
            return self.Width * self.Len * self.Height
    
    r1 = Room('zhangshan',10,20,30)
    v = r1.cal_volume # 以属性的方式调用
    print(v) # 6000
    print(r1.__dict__) # {'Name': 'zhangshan', 'Width': 10, 'Len': 20, 'Height': 30}
    View Code

    静态方法

    @staticmethod
    一个类的工具包,只是名义上归属类管理,不能使用类变量和实例变量
    class Room:
        num = 2046
        def __init__(self,name,width,length,height):
            self.Name = name
            self.Width = width
            self.Len = length
            self.Height = height
    
        @property
        def cal_volume(self):
            return self.Width * self.Len * self.Height
        @classmethod
        def tell_info(cls,adress):
            print("类方法:%s,%d" %(adress,cls.num))
    
        @staticmethod
        def clean_room(name):
            print("%s打扫room" %(name))
    
    Room.clean_room("lisi")
    r1 = Room('zhangshan',10,20,30)
    r1.clean_room("zhangshan")
    View Code
     

    类方法

    @classmethod

    类调用自己的方法,跟实例没有什么关系

    class Room:
        num = 2046
        def __init__(self,name,width,length,height):
            self.Name = name
            self.Width = width
            self.Len = length
            self.Height = height
    
        @property
        def cal_volume(self):
            return self.Width * self.Len * self.Height
        @classmethod
        def tell_info(cls,adress):
            print("类方法:%s,%d" %(adress,cls.num))
    
    Room.tell_info('门牌号') # 类方法:门牌号,2046
    View Code

    组合

    定义一个人的类,人有头、躯干、手脚等数据属性,这几个属性又可以是通过一个类实例化的对象,这就是组合

    用途:

    1.做关联

    2.小的组成大的

    class Hand:
        pass
    class Foot:
        pass
    class Head:
        pass
    class Trunk:
        pass
    
    class Person:
        def __init__(self,id,name):
            self.Id = id
            self.Name = name
            self.hand = Hand()
            self.foot = Foot()
            self.head = Head()
            self.trunk = Trunk()
    
    print(Person.__dict__)
    '''
    {'__module__': '__main__', '__init__': <function Person.__init__ at 0x01689738>, 
    '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>,
     '__doc__': None}
    '''
    p1 = Person(2046,'zhangsan')
    print(p1.__dict__)
    '''
    {'Id': 2046, 'Name': 'zhangsan', 'hand': <__main__.Hand object at 0x021F7FF0>, 
    'foot': <__main__.Foot object at 0x021FF030>, 'head': <__main__.Head object at 0x021FF070>, 
    'trunk': <__main__.Trunk object at 0x021FF090>}
    '''
    View Code
    class School:
        def __init__(self,name,addr):
            self.Name = name
            self.Addr = addr
        def zhao_sheng(self):
            print("%s 正在招生" %(self.Name))
    
    class Course:
        def __init__(self,lesson,price,period,school):
            self.Lesson = lesson
            self.Price = price
            self.Period = period
            self.Sch = school
    
    s1 = School('Tihuang','Peking')
    s2 = School('Beida','Peking')
    s3 = School('TimeL','shenzhen')
    
    # L = Course("linux",1000,4,s1)
    # print(L.__dict__) #{'Lesson': 'linux', 'Price': 1000, 'Period': 4, 'Sch': <__main__.School object at 0x02497F90>}
    #
    # L.Sch.zhao_sheng()
    
    menu = {
        "1":s1,
        "2":s2,
        "3":s3
    }
    
    s = input(">>:")
    obj = menu[s]
    L = Course("linux",1000,4,obj)
    L.Sch.zhao_sheng()
    print(L.Sch.Name,L.Sch.Addr)
    View Code
  • 相关阅读:
    《棉花帝国:一部资本主义全球史》笔记
    关于”空杯之心“的重新思考
    《光荣与梦想:19321972年美国叙事史》笔记
    《哥伦布大交换:1492年以后的生物影响和文化冲击》笔记
    《增长、短缺与效率》笔记
    《逃不开的经济周期:历史、理论与投资现实》笔记
    《经济学》笔记
    《就业、利息和货币通论》笔记
    PostgreSQL与MySQL比较
    让svn自动更新代码注释中的版本号
  • 原文地址:https://www.cnblogs.com/xiangtingshen/p/10453779.html
Copyright © 2011-2022 走看看