码迷,mamicode.com
首页 > 编程语言 > 详细

python 类 二: 类的属性

时间:2016-10-04 08:12:56      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:   python   属性   


类有数据属性和方法属性:


属性就是 一个对象的数据成员或者函数成员。


类的数据属性只有被类的实例引用后去更新或者被类定义的可以访问这个数据属性的方法去改变( 也要通过类的实例化)。


也可以说,类的数据属性是跟类绑定的,类的数据属性是不受任何实例化的对象所影响的。


有两种方法可以去访问类的属性,一种是dir(),一种是 class.__dict__属性


dir() 可以看到对象的属性的名字列表。

类的内置属性 __dict__  则可以返回一个字典,对应的是 属性名 键值 的对应关系 。也就是返回的是对象的属性名和属性值的对应关系。


下面是个简单的对类的 dir()  和 类的内置 __dict__方法看到的属性不同的代码例子:


[root@puppet-master-231-test eg_4]# cat !$
cat class_property.py
#coding:utf-8

class demo(object):
    ‘demo for class property‘
    def __init__(self,testname):
        self.name = testname
    def update_name(self,newname):
        self.name = newname

print dir(demo)
print 
print demo.__dict__
[root@puppet-master-231-test eg_4]# 
[root@puppet-master-231-test eg_4]# 
[root@puppet-master-231-test eg_4]# 
[root@puppet-master-231-test eg_4]# 
[root@puppet-master-231-test eg_4]# python2.7  class_property.py
[‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__module__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘, ‘update_name‘]

{‘update_name‘: <function update_name at 0x7febc61b4c80>, ‘__module__‘: ‘__main__‘, ‘__dict__‘: <attribute ‘__dict__‘ of ‘demo‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘demo‘ objects>, ‘__doc__‘: ‘demo for class property‘, ‘__init__‘: <function __init__ at 0x7febc61b4c08>}


  

  

本文出自 “linux与网络那些事” 博客,请务必保留此出处http://khaozi.blog.51cto.com/952782/1858503

python 类 二: 类的属性

标签:   python   属性   

原文地址:http://khaozi.blog.51cto.com/952782/1858503

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!