• Python 面向对象之一 类与属性


    Python 面向对象之 类与属性

        今天接触了一下面向对象,发现面向对象和之前理解的简直就是天壤之别,在学Linux的时候,一切皆文件,现在学面向对象了,so,一切皆对象。

        之前不是一直在学的用面向函数编程,用函数就可以搞定一切了,但是为啥要用面向对象?面向对象呢,大大的提高了程序的可扩展性,面对不停的需求改变的时候,面向对象的优越性就展现出来了,先从面向函数来向面向对象进行过度。

    先举一个例子:

    # def dog(name,gender,type):
    #     # 狗的动作
    #     def jiao(dog):
    #         print('一条狗[%s],汪汪汪' % dog['name'])  #此处可以与函数名dog或者与字典的返回值do同名都可以(最好还是要以返回值相同)
    #     def chi_fan(dog):
    #         print('一条[%s] 正在吃饭' % dog['type'])
    #     dog = {
    #         'name':name,
    #         'gender': gender,
    #         'type': type,
    #         'jiao':jiao,
    #         'chi_shi':chi_fan,
    #     }
    #     return dog
    # d1=dog('牛逼','公','中华犬')
    输出的结果:
    #{'name': '牛逼', 'gender': '公', 'type': '中华犬', 'jiao': <function dog.<locals>.jiao at 0x005912B8>, 'chi_fan': <function dog.<locals>.chi_shi at 0x00591270>}
    
    

    从上面的例子可以看出:定义了一个dog函数,在这个函数内呢又定义了函数jiao和 chi_fan 两个函数,还定义了一个字典,在这个字典中呢有定义dog的数据属性,比如:名字,性别等,还有函数属性 叫和吃饭,在函数最后有一个返回值return 返回的呢是dog 这个字典,打印d1的数值就会发现:得到的是一个字典类型的数据,其中函数属性返回的是函数的内存地址。

    在此基础上进行改进:

    def dog(name,gender,type):
    #     # 狗的动作
    #     def jiao(dog):
    #         print('一条狗[%s],汪汪汪' % dog['name'])
    #     def chi_fan(dog):
    #         print('一条[%s] 正在吃饭' % dog['type'])
    #     def init(name,gender,type):#狗的属性和狗的方法(将返回值也做成一个方法来使用)
    #         dog1 = {
    #             'name':name,
    #             'gender': gender,
    #             'type': type,
    #             'jiao':jiao,
    #             'chi_shi':chi_fan,
    #         }
    #         return dog1
    #     return init(name,gender,type)  # (将函数名当参数进行传递)
    #
    # d1=dog('牛逼','公','中华犬')
    # print(d1)
    # d1['jiao'](d1)   #jiao 函数需要传入参数,参数为d1这个狗
    
    
    输出结果:一条狗[牛逼],汪汪汪

    这一次是在之前的基础上把返回值做成一个init的函数通过这个函数来执行字典里面的内容,若是要调用定义def dog中的方法,调用方式为:d1['jiao'](d1) #调用字典的值加括号进行运此函数。

    是不是还是面向函数实现了把dog 的属性和方法封装在函数中实现了,好了接下来用面向对象来实现上述的功能:

    class Dog:
        def __init__(self,name,gender,type):
            self.name = name
            self.gender = gender
            self.type = type
        def jaio(self,):
            print('一条叫%s 的狗在大声的叫'%(self.name))
    
        def chi_fan(self,):
            print('一条叫%s 的狗在吃饭'%(self.name))
    
    d1 = Dog('牛逼','male','')
    print(d1) # <__main__.Dog object at 0x004D6690>
    print(d1.__dict__) # {'name': '牛逼', 'gender': 'male', 'type': '公'}
    d1.chi_fan() # 一条叫牛逼 的狗在吃饭

    好现在总结一下,类:就是把一类事物的相同特征和动作整合在一起就是类,类就是一个抽象概念。对象:就是基于类创建的一个具体的事物(具体存在的),也是把动作和特征结合在一起。

    接下来看一下类的数据属性和函数属性:

    class Chinese:
        '中国人的类'
        ren='中国人'
        def watch_tv(self):
            print('好牛逼的剧')
        def cha_dui(self):
            print('插到了前面')
    
    print(Chinese.ren)
    Chinese.watch_tv('kjk')
    Chinese.cha_dui('就是你')
    #
    print(dir(Chinese)) #查看存在的方法
    print(Chinese.__dict__) #查看类的属性字典
    print(Chinese.__dict__['ren'])
    Chinese.__dict__['watch_tv'](1)
    Chinese.__dict__['cha_dui'](1)
    
    #输出结果为:中国人
    好牛逼的剧
    插到了前面
    ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'cha_dui', 'ren', 'watch_tv']
    {'__module__': '__main__', '__doc__': '中国人的类', 'ren': '中国人', 'watch_tv': <function Chinese.watch_tv at 0x008112B8>, 'cha_dui': <function Chinese.cha_dui at 0x00811270>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>}
    中国人
    好牛逼的剧
    插到了前面

    类属性的增删改查:

    class Chinese:
        country='China'
        def __init__(self,name):
            self.name=name
    
        def play_ball(self,ball):
            print('%s 正在打 %s' %(self.name))
    #查看
    print(Chinese.country)
    #
    # #修改
    Chinese.country='Japan'
    print(Chinese.country)
    #
    p1=Chinese('alex')
    print(p1.__dict__)#返回的是p1对象中init中存储的字典数据属性
    print(p1.country) #首先在p1的数据属性中找若此数值不存在则在类的数据属性中找
    #
    # #增加
    Chinese.ren='中国人'
    #
    print(Chinese.ren)
    print(p1.ren) #首先在p1的数据属性中找若此数值不存在则在类的数据属性中找
    
    # #删除
    del Chinese.ren
    del Chinese.country
    #
    # print(Chinese.__dict__)
    # print(Chinese.country)  #AttributeError: type object 'Chinese' has no attribute 'country'
    
    
    #增加方法
    def eat_food(self,food):
        print('%s 正在吃%s' %(self.name,food))
    #
    Chinese.eat=eat_food  #{'__module__': '__main__', '__init__': <function Chinese.__init__ at 0x021E1300>, 'play_ball': <function Chinese.play_ball at 0x021E12B8>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None, 'eat': <function eat_food at 0x021E1348>}
    #
    print(Chinese.__dict__)
    p1.eat('') #alex 正在吃饭
    #

    实例属性的增删改查:

    class Chinese:
        country='China'
        def __init__(self,name):
            self.name=name
    
        def play_ball(self,ball):
            print('%s 正在打 %s' %(self.name,ball))
    
    p1=Chinese('牛逼') #实例化一个对象p1
    print(p1.__dict__) #打印p1中存在的所有属性(实例化对象中只存在数值型属性)
    
    #查看
    print(p1.name)
    print(p1.play_ball) # bound method Chinese.play_ball of <__main__.Chinese object at 0x00426690>>
    
    # #增加
    p1.age=18
    print(p1.__dict__)
    print(p1.age)
    #
    
    #
    # #修改
    p1.age=19
    print(p1.__dict__)
    print(p1.age)
    #
    # #删除
    del p1.age
    print(p1.__dict__)

    获取类属性和实例化的属性举例:

    class Chinese:
        country='China'
        l=['a','b']
        def __init__(self,name):
            self.name=name
    
        def play_ball(self,ball):
            print('%s 正在打 %s' %(self.name,ball))
    p1=Chinese('sb')
    print(p1.l) #现去p1的init中找,若没有就会去类Chinese中去找类的数据属性
    p1.l=[1,2,3] #是给实例化对象p1中添加一个数据属性 'l': [1, 2, 3]
    print(Chinese.l) #['a', 'b']
    print(p1.__dict__) #{'name': 'sb', 'l': [1, 2, 3]}
    p1.l.append('c')
    print(p1.__dict__) #{'name': 'sb', 'l': [1, 2, 3, 'c']}
    print(Chinese.l) #['a', 'b']
    
    
    country='中国-------------------'
    class Chinese:
        country='中国'
        def __init__(self,name):
            self.name=name
            print('--->',country)
    
        def play_ball(self,ball):
            print('%s 正在打 %s' %(self.name,ball))
    
    #print(Chinese.__dict__)  # {'__module__': '__main__', 'country': '中国', '__init__': <function Chinese.__init__ at 0x006E1300>, 'play_ball': <function Chinese.play_ball at 0x006E12B8>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None}
    #print(Chinese.country)  #中国
    p1=Chinese('sb') #---> 中国-------------------
    print('实例--------》',p1.country) #实例--------》 中国
    
    #注意:通过点(.)来访问变量时在类class中去寻找,而一般变量不是通过实例化对象或类名点的方式去访问,则这个是在类的外面去寻找这个变量。
  • 相关阅读:
    Leetcode 811. Subdomain Visit Count
    Leetcode 70. Climbing Stairs
    Leetcode 509. Fibonacci Number
    Leetcode 771. Jewels and Stones
    Leetcode 217. Contains Duplicate
    MYSQL安装第三步报错
    .net 开发WEB程序
    JDK版本问题
    打开ECLIPSE 报failed to load the jni shared library
    ANSI_NULLS SQL语句
  • 原文地址:https://www.cnblogs.com/haishiniu123/p/6786065.html
Copyright © 2020-2023  润新知