Pthon面向对象-特殊属性

                                      作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

一.特殊属性

  1. #!/usr/bin/env python
  2. #_*_conding:utf-8_*_
  3. #@author :yinzhengjie
  4. #blog:http://www.cnblogs.com/yinzhengjie
  5.  
  6. class Person:
  7. """
  8. This is Class doc .
  9. """
  10. def __init__(self,name,age = 18):
  11. """
  12. This is instance doc .
  13. """
  14. self.__name = name
  15. self.__age = age
  16.  
  17. @property
  18. def name(self):
  19. return self.__name
  20.  
  21. @name.setter
  22. def name(self,name):
  23. self.__name = name
  24.  
  25. p1 = Person("Jason Yin",20)
  26. print(p1.name)
  27.  
  28. print(Person.__name__,p1.__class__.__name__) #显示类,函数,方法的名称
  29.  
  30. print(Person.__module__,p1.__module__) #显示类所在的模块名
  31.  
  32. print(Person.__class__,p1.__class__) #类或者对象所属的类
  33.  
  34. print(Person.__bases__) #类的基类的元组,顺序为他们在基类列表中出现的顺序
  35.  
  36. print(Person.__doc__,p1.__doc__) #类,函数的文档字符串,如果没有定义则为None
  37.  
  38. print(Person.__mro__) #类的mro(Method Resolution Order),即方法解析顺序,它和"class.mro()"返回的结果保存在"__mro__"中
  39.  
  40. print(Person.__dict__,p1.__dict__) #类或者实例的属性,可写的字典
  41.  
  42. print(Person.__dir__,p1.__dir__()) #返回类或者对象的所有成员名称列表

二.查看属性

1>.__dir__ 方法

  1.   该属性返回类或者对象的所有成员名称列表。dir()函数操作实例就是调用__dir__()。
  2.  
  3.   如果dir([obj])的obj包含方法__dir__(),该方法将被调用。如果参数obj不包含__dir__(),该方法将最大限度地收集属性信息。

2>.dir(obj)对于不同的对象具有不同的行为

  1.   如果对象是模块对象,返回的列表包含模块的属性名和变量名。
  2.  
  3.   如果对象是类型或者说是类对象,返回的列表包含类的属性名及它的祖先类的属性名。
  4.  
  5.   如果是类的实例需要注意以下两点:
        __dir__方法,返回可迭代对象的返回值。
        没有__dir__方法,则尽可能收集实例的属性名,类的属性和祖先类的属性名。
  6.  
  7.   如果obj不写,返回列表包含内容不同。
        在模块中,返回模块的属性和变量名。
        在函数中,返回本地作用域的变量名。
        在方法中,返回本地作用域的变量名。

3>.animal.py测试内容

  1. #!/usr/bin/env python
  2. #_*_conding:utf-8_*_
  3. #@author :yinzhengjie
  4. #blog:http://www.cnblogs.com/yinzhengjie
  5.  
  6. class Animal:
  7. x = 123
  8. def __init__(self,name):
  9. self._name = name
  10. self.__age = 10
  11. self.weight = 20
  12.  
  13. print('Animal module \'s names = {}'.format(dir())) #显示模块的属性名称
  14.  
  15. #以上代码执行结果如下:
  16. Animal module 's names = ['Animal', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

4>.test.py(需要用到上面animal模块)

  1. #!/usr/bin/env python
  2. #_*_conding:utf-8_*_
  3. #@author :yinzhengjie
  4. #blog:http://www.cnblogs.com/yinzhengjie
  5.  
  6. import animal
  7. from animal import Animal
  8.  
  9. class Cat(Animal):
  10. name = '布偶'
  11. age = 3
  12.  
  13. class Dog(Animal):
  14. def __dir__(self):
  15. return ["dog"] #"__dir__"魔术方法必须返回可迭代对象。
  16.  
  17. print("{0} 我是分割线 {0}".format("*" * 20))
  18.  
  19. print("Current module\'s names = {}".format(dir())) #模块名词空间内的属性
  20.  
  21. print("animal module\'s names = {}".format(dir(animal))) #指定模块名称空间内的属性
  22.  
  23. print("Animal's dir() = {}".format(dir(Animal))) #类Animal的dir()
  24.  
  25. print("Cat's dir() = {}".format(dir(Cat))) #类Cat的dir()
  26.  
  27. print("Dog's dir() = {}".format(dir(Dog))) #类Dog的dir()
  28.  
  29. print("object's __dict__ = {}".format(sorted(object.__dict__.keys()))) #查看object的字典
  30.  
  31. print("{0} 我是分割线 {0}".format("*" * 20))
  32.  
  33. tom = Cat('Tom')
  34. print(sorted(dir(tom))) #实例tom 的属性,Cat类及所有祖先类的类属性
  35. print(sorted(tom.__dir__())) #同上,因此我们可以总结dir方法等效于下面的写法
  36. print(sorted(set(tom.__dict__.keys())| set(Cat.__dict__.keys()) | set(object.__dict__.keys())))
  37.  
  38. print("{0} 我是分割线 {0}".format("*" * 20))
  39.  
  40. dog = Dog('二哈')
  41. print(dir(dog))
  42. print(dog.__dict__)
  43.  
  44. #以上代码执行结果如下:
  45. Animal module 's names = ['Animal', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
  46. ******************** 我是分割线 ********************
  47. Current module's names = ['Animal', 'Cat', 'Dog', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'animal']
  48. animal module's names = ['Animal', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
  49. Animal's dir() = ['__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__', 'x']
  50. Cat's dir() = ['__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__', 'age', 'name', 'x']
  51. Dog's dir() = ['__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__', 'x']
  52. object's __dict__ = ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
  53. ******************** 我是分割线 ********************
  54. ['_Animal__age', '__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__', '_name', 'age', 'name', 'weight', 'x']
  55. ['_Animal__age', '__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__', '_name', 'age', 'name', 'weight', 'x']
  56. ['_Animal__age', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_name', 'age', 'name', 'weight']
  57. ******************** 我是分割线 ********************
  58. ['dog']
  59. {'_name': '二哈', '_Animal__age': 10, 'weight': 20}

5>.内建函数locals(),globals()与dir()之间的关系

  1. #!/usr/bin/env python
  2. #_*_conding:utf-8_*_
  3. #@author :yinzhengjie
  4. #blog:http://www.cnblogs.com/yinzhengjie
  5.  
  6. """
  7. locals() 返回当前作用域中的变量字典
  8. globals() 当前模块全局变量的字典
  9. """
  10.  
  11. class Person:
  12. def show(self):
  13. a = 100
  14. t = int(a)
  15. print(dir())
  16. print(locals())
  17.  
  18. def test(a=50,b=100):
  19. c = 150
  20. print(dir())
  21. print(locals())
  22.  
  23. Person().show()
  24.  
  25. print("{0} 我是分割线 {0}".format("*" * 20))
  26.  
  27. test()
  28.  
  29. print("{0} 我是分割线 {0}".format("*" * 20))
  30.  
  31. print(dir())
  32. print(sorted(locals().keys()))
  33. print(sorted(globals().keys()))
  34.  
  35. #以上代码执行结果如下:
  36. ['a', 'self', 't']
  37. {'self': <__main__.Person object at 0x0000015CDA8D7448>, 'a': 100, 't': 100}
  38. ******************** 我是分割线 ********************
  39. ['a', 'b', 'c']
  40. {'a': 50, 'b': 100, 'c': 150}
  41. ******************** 我是分割线 ********************
  42. ['Person', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'test']
  43. ['Person', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'test']
  44. ['Person', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'test']

Pthon面向对象-特殊属性的更多相关文章

  1. Pthon面向对象-补充知识

    Pthon面向对象-补充知识 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.tracemalloc 标准库tracemalloc,可以统计内存使用情况,通过下面的案例可以看出内 ...

  2. Pthon面向对象-异常处理

    Pthon面向对象-异常处理 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.异常概述 1>.错误(Error) 逻辑错误: 算法写错了,例如加法写成了减法. 笔误: 例如 ...

  3. 理解JAVA - 面向对象(object) - 属性,方法

    理解JAVA - 面向对象(object) - 属性,方法 多态的体现:    向上造型,父类接收子类对象:向上造型:    从父类角度看不到子类独有的方法:面向对象,人类认知世界的方式:生活中每天都 ...

  4. python 面向对象 私有属性

    __init__构造函数 self.name = name # 属性, 实例变量,成员变量,字段 def sayhi()# 方法, 动态属性 私有属性不对外看到 前面加上__ class role() ...

  5. python入门(十四):面向对象(属性、方法、继承、多继承)

    1.任何东西1)属性(特征:通常可以用数据来描述)(类变量和实例变量)2)可以做一些动作(方法) 类来管理对象的数据.属性:类变量和实例变量(私有变量)方法:    1)实例方法    2)类方法   ...

  6. python 面向对象 公有属性

    公有属性定义  公有属性也叫作类变量  静态字段 class role(): # 传参数 # 公有属性都在这里定义 # 在类里直接定义的属性即是公有属性 nationality = 'JP' def ...

  7. 面向对象property属性、静态方法和类方法

    一.property属性 1.什么是property特性? property是一种特殊的属性,访问它时会执行一段功能(函数)然后返回值. from math import pi class Circl ...

  8. Python面向对象之类属性类方法静态方法

    类的结构 实例 使用面向对象开发时,第一步是设计类: 当使用 类名() 创建对象时,会自动执行以下操作: 1.为对象在内存中分配空间--创建对象: 2.为对象的属性 设置初始值--初始化方法(init ...

  9. ~~核心编程(二):面向对象——类&属性~~

    进击のpython 类&属性 虽然我们上一part写了一个面向对象的程序:人狗大战 但是如果在面向对象来看 你这些的就不够规范 你既然选择用面向对象的思想来写 那你就要符合人家的定义规范和操作 ...

随机推荐

  1. vue-cli3项目关闭烦人的代码检测

    参考博客:https://blog.csdn.net/e1172090224/article/details/99636767 vue.config.js module.exports = { lin ...

  2. 【并行计算-CUDA开发】【视频开发】ffmpeg Nvidia硬件加速总结

    2017年5月25日 0. 概述 FFmpeg可通过Nvidia的GPU进行加速,其中高层接口是通过Video Codec SDK来实现GPU资源的调用.Video Codec SDK包含完整的的高性 ...

  3. OpenLDAP + phpLDAPadmin

    一.基础设置 1.1 环境说明 Centos 7.5 openldap 1.2 关闭防火墙和selinux setenforce sed -i 's/SELINUX=enforcing/SELINUX ...

  4. Access to XMLHttpRequest at 'http://127.0.0.1:8000/XXXXX' from origin 'http://localhost

    Django 报错,跨域请求出现问题. 在settings.py中添加 #设置可跨域范围 CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = T ...

  5. mysql 启动 && 停止

    启动:service mysql start关闭:service mysql stop查进程:ps aux | grep mysql杀进程:kill -9 mysqlID Good Good Stud ...

  6. Java设计RestfulApi接口,实现统一格式返回

    创建返回状态码枚举 package com.sunny.tool.api.enums; /** * @Author sunt * @Description 响应枚举状态码 * @Date 2019/1 ...

  7. Python学习之路:函数传递可变参数与不可变参数

    函数传参的方法: 太基础了,8说了 直接上重点 一.可变参数的传递 可变参数有:列表.集合.字典 直接上代码: a = [1, 2] def fun(a): print('传入函数时a的值为:', a ...

  8. 远程登录Linux系统(使用xshell),远程上传加载文件(使用Xftp)

    一.Xshell(远程登录Linux系统) 1.安装xshell 自己百度找安装包 2.连接登录 1.连接前提 需要Linux开启一个sshd的服务,监听22号端口,一般默认是开启的 查看是否开启: ...

  9. redis-集群(codis和Cluster)

    codis 和 cluster 对比图: codis工作图: cluster工作图:(去中心化)

  10. [cf 1245 F] Daniel and Spring Cleaning

    题意: 求区间$[l,r]$内有多少有序数对$(a,b)$满足$a+b=a\bigoplus b$. $l,r\leq 10^9$. 题解: 有用的就一句话: 求区间内一元组可以一维容斥,同理求二元组 ...