直奔主题

使用中文注释需要使用

#-*-coding:utf-8-*-

property

property在python中有2中使用property方法:
1.@property @属性名称.setter @属性名称.deleter
2.使用property(fget, fset, fdel, doc)指定

1.使用装饰器@property
要求:(1)所用的类为新式类,在python3版本以上默认为新式类,或者是是直接或间接继承object的类
(2)定义的函数名称必须要是名称名(如属性名是name,那函数名称就为name,不能为其他的。详情看例子)

class Demo(object):
def __init__(self):
print("这是构造函数")
self._name = None @property
def name(self):
return self._name #这是属性get的方法 @name.setter
def name(self, value):#这是属性set的方法
self._name = value @name.deleter
def name(self):
print("this is the method of delete")
self._name = None if __name__ == "__main__":
testDemo = Demo()
print(testDemo.name)
testDemo.name = "name"
print(testDemo.name)
del testDemo.name

以下是结果:

#======以下是结果========
这是构造函数
None
name
this is the method of delete

2.使用property()方法 property(fget,fset,fdel,doc)
要求:(1)所用的类为新式类,在python3版本以上默认为新式类,或者是是直接或间接继承object的类

class Demo2(object):
def __init__(self):
print("这是构造函数")
self._value = None def getValue(self):#这是属性value的get方法
print("getting the value of property")
return self._value def setValue(self, value):#这是属性value的set方法
print("setting the value of property")
self._value = value def delValue(self):#这是属性value删除方法
print("this is the method of delete")
self._value = None value = property(fget=getValue, fset=setValue, fdel=delValue, doc="this is a message about the property of value") if __name__ == "__main__":
testDemo = Demo2()
print(testDemo.value)
testDemo.value = "name"
print("print the value of property:",testDemo.value)
del testDemo.value

以下是结果:

#======以下是结果========
这是构造函数
getting the value of property
None
setting the value of property
getting the value of property
('print the value of property:', 'name')
this is the method of delete

使用属性property2种方法存放多个值的例子

1.使用装饰器@property进行设置 属性含有多个值

class Demo4(object):
def __init__(self):
print("这是构造函数")
self._value1 = None
self._value2 = None @property
def values(self):
return self._value1, self._value2 #这是属性get的方法 @values.setter
def values(self, values):#这是属性set的方法
self._value1, self._value2 = values @values.deleter
def values(self):
print("this is the method of delete")
self._value1 = None
self._value2 = None if __name__ == "__main__":
testDemo = Demo4()
print(testDemo.values)
testDemo.values = "name","helloworld"
print("print the value of property:", testDemo.values)
del testDemo.values

以下是结果:

#======以下是结果========
这是构造函数
(None, None)
('print the value of property:', ('name', 'helloworld'))
this is the method of delete

2.property(fget, fset, fdel, doc)方法设置  属性含有多个值

class Demo3(object):
def __init__(self):
print("这是构造函数")
self._value = None
self._value2 = None def getoValue(self): # 这是属性value的get方法
print("getting the value of property")
return self._value, self._value2 def setoValue(self, values): # 这是属性value的set方法
print("setting the value of property")
self._value, self._value2 = values def deloValue(self): # 这是属性value删除方法
print("this is the method of delete")
self._value = None values = property(fget=getoValue, fset=setoValue, fdel=deloValue, doc="this is a message about the property of values") if __name__ == "__main__":
testDemo = Demo3()
print(testDemo.values)
testDemo.values = "name","helloworld"
print("print the value of property:", testDemo.values)
del testDemo.values

以下是结果:

这是构造函数
getting the value of property
(None, None)
setting the value of property
getting the value of property
('print the value of property:', ('name', 'helloworld'))
this is the method of delete

getter和setter

getter和setter 是在对象上动态的增加属性

if __name__ == "__main__":
testDemo = Demo2() print([n for n in dir(testDemo) if n[0] is not "_"])
setattr(testDemo, "newMethod", "hellworld")
print([n for n in dir(testDemo) if n[0] is not "_"])
value = getattr(testDemo, "newMethod")
print(value)
#使用getattr获取一个不存在的属性,如果属性不存在,则返回一个默认的值
value = getattr(testDemo, "yoyo", "the value is not exist!")
print(value)

以下是结果:

#======以下是结果========
这是构造函数
['delValue', 'getValue', 'setValue', 'value']
['delValue', 'getValue', 'newMethod', 'setValue', 'value']
hellworld
the value is not exist!

python 属性 property、getattr()、setattr()详解的更多相关文章

  1. Python中的getattr()函数详解

    最近看Dive into python第四章自省中提到getattr()函数,作为一个内建函数平时自己没怎么用过所以也不太理解这个函数的一些用法 看了下函数本身的doc getattr(object, ...

  2. 【转】Python的hasattr() getattr() setattr() 函数使用方法详解

    Python的hasattr() getattr() setattr() 函数使用方法详解 hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOOL值 ...

  3. Python包模块化调用方式详解

    Python包模块化调用方式详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一般来说,编程语言中,库.包.模块是同一种概念,是代码组织方式. Python中只有一种模块对象类型 ...

  4. 【Python】Python内置函数dir详解

    1.命令介绍 最近学习并使用了一个python的内置函数dir,首先help一下: 复制代码代码如下: >>> help(dir)Help on built-in function ...

  5. Python API 操作Hadoop hdfs详解

    1:安装 由于是windows环境(linux其实也一样),只要有pip或者setup_install安装起来都是很方便的 >pip install hdfs 2:Client——创建集群连接 ...

  6. python设计模式之装饰器详解(三)

    python的装饰器使用是python语言一个非常重要的部分,装饰器是程序设计模式中装饰模式的具体化,python提供了特殊的语法糖可以非常方便的实现装饰模式. 系列文章 python设计模式之单例模 ...

  7. Python调用windows下DLL详解

    Python调用windows下DLL详解 - ctypes库的使用 2014年09月05日 16:05:44 阅读数:6942 在python中某些时候需要C做效率上的补充,在实际应用中,需要做部分 ...

  8. Python安装、配置图文详解(转载)

    Python安装.配置图文详解 目录: 一. Python简介 二. 安装python 1. 在windows下安装 2. 在Linux下安装 三. 在windows下配置python集成开发环境(I ...

  9. 【和我一起学python吧】Python安装、配置图文详解

     Python安装.配置图文详解 目录: 一. Python简介 二. 安装python 1. 在windows下安装 2. 在Linux下安装 三. 在windows下配置python集成开发环境( ...

  10. Python中的高级数据结构详解

    这篇文章主要介绍了Python中的高级数据结构详解,本文讲解了Collection.Array.Heapq.Bisect.Weakref.Copy以及Pprint这些数据结构的用法,需要的朋友可以参考 ...

随机推荐

  1. 【pb_ds】bzoj1056 [HAOI2008]排名系统/bzoj1862 [Zjoi2006]GameZ游戏排名系统

    STL裸题,线下AC,bzoj无限RE ing…… #include<cstdio> #include<cctype> #include<iostream> #in ...

  2. 【可持久化Trie】bzoj3261 最大异或和

    对原序列取前缀异或值,变成pre[1...N],然后询问等价于求max{a[N]^x^pre[i]}(l-1<=i<=r-1). #include<cstdio> #defin ...

  3. Python的编码注释# -*- coding:utf-8 -*-

    # -*- coding:utf-8 -*-的主要作用是指定文件编码为utf-8, 因为一般默认的是ASCII码,如果要在文件里面写中文,运行时会出现乱码,加上这句之后会把文件编码强制转换为utf-8 ...

  4. 基于tiny4412的u-boot移植(二)

    作者信息 作者:彭东林 邮箱:pengdonglin137@163.com QQ: 405728433 平台介绍 开发环境:win7 64位 + VMware11 + Ubuntu14.04 64位 ...

  5. 【spring mvc】spring mvc POST方式接收单个字符串参数,不加注解,接收到的值为null,加上@RequestBody,接收到{"uid":"品牌分类大”},加上@RequestParam报错 ---- GET方式接收单个参数的方法

    spring mvc POST方式 接收单个参数,不加任何注解,参数名对应,接收到的值为null spring mvc POST方式 接收单个参数,加上@RequestBody,接收到参数格式:{&q ...

  6. 降低web服务器压力

    一.越来越多的并发连接数 现在的Web系统面对的并发连接数在近几年呈现指数增长,高并发成为了一种常态,给Web系统带来不小的挑战.以最简单粗暴的方式解决,就是增加Web系统的机器和升级硬件配置.虽然现 ...

  7. JS中event.preventDefault()取消默认事件能否还原?

    参考知乎讨论:https://www.zhihu.com/question/21891734

  8. meta文件里指定资源

    unity的黑科技 https://github.com/keijiro/KinoFringe/tree/master/Assets/Kino 这个包里面 shader的绑定很有意思在meta里面 d ...

  9. sql where 1=1和 0=1 的作用(多条件查询错误的问题)

    where 1=1; 这个条件始终为True,在不定数量查询条件情况下.1=1能够非常方便的规范语句. 一.不用where  1=1  在多条件查询中的困扰 举个样例,假设您做查询页面,而且.可查询的 ...

  10. 文档对象模型-DOM(二)

    从NodeList中选择元素 方法一:item()方法,用于返回其中的单一节点,需要在方法的参数中指定所需元素的索引编号. 当其中没有任何元素时,执行代码是对资源的浪费.因此程序员会在执行代码之前,先 ...