请利用@property给一个Screen对象加上widthheight属性,以及一个只读属性resolution

写了一段代码

class Screen(object):
#利用property装饰器负责把width方法变成属性调用
@property
def width(self):
return self._width
#定义setter方法变成可读属性,如果不定义getter方法,就是只读属性
@width.setter
def width(self, value):
self._width = value
#同width
@property
def height(self):
return self._height
#同width
@height.setter
def height(self, value):
self._height = value
#将resolution变成一个只读属性,并打印出来
@property
def resolution(self):
print("%s * %s == %d" %(self._width, self._height, self._width*self._height))

测试一下,#test

s = Screen()
s.width = 1024
s.height = 768
s.resolution

输出结果:

1024 * 768 == 786432

上面是一个简单没有进行属性控制的语句,能够实现功能,但在网上看到另外一种情况,就是要对相关方法属性进行raise抛出异常操作

增加了一个@staticmethod 静态方法,觉得挺好,后来又看到了除了staticmethod静态方法还有classmethod类方法,在这里也普及一下

改进后的代码

class Screen(object):
def __init__(self):
self._height = 0
self._width = 0 @staticmethod
def _check_param(value):
if not isinstance(value, int):
raise TypeError('必须是一个整数类型!')
if value <= 0:
raise ValueError('必须是大于0的数!') #利用property装饰器负责把width方法变成属性调用
@property
def width(self):
return self._width
#定义setter方法变成可读属性,如果不定义getter方法,就是只读属性
@width.setter
def width(self, value):
self._check_param(value)
self._width = value
#同width
@property
def height(self):
return self._height
#同width
@height.setter
def height(self, value):
self._check_param(value)
self._height = value
#将resolution变成一个只读属性,并打印出来
@property
def resolution(self):
print("%s * %s == %d" %(self._width, self._height, self._width*self._height))

测试一下:

s = Screen()
s.width = -1024

输出:ValueError: 必须是大于0的数!

接下来看一下之前的问题staticmethod和classmethod方法,参考:http://www.cnblogs.com/Tony-zhangl/p/4687889.html

static method定义:静态方法是一类特殊的方法。有时,你想写一些属于类的代码,但又不会去使用和这个类任何相关的东西。(很抽象),基本上和一个全局函数差不多,可以通过类或者类的实例对象进行调用,不会隐式地传入任何参数。

class method定义:什么是类方法,类方法不是绑定到类的实例上去的,而是绑定到类上去的.(也很抽象),是和一个class类相关的方法,可以通过类或类实例进行调用,并将该class对象(不是class的实例对象)隐式地当作第一个参数传入。

区别:类方法需要额外的类变量cls,调用类方法传入的类变量cls是子类,而不是父类。类方法和静态方法都可以通过类对象和类的实例对象访问。

class MyClass(object):
var = "test for myclass" @classmethod
def clsmethod(cls):
print(cls.var)
@staticmethod
def sticmethod():
print(MyClass.var)

s = MyClass()
s.clsmethod()
s.sticmethod()

输出结果

s.clsmethod()
test for myclass

s.sticmethod()  
test for myclass

另外一个显然的对比例子如下

class ParentClass(object):

    var = "test for parent"

    @classmethod
def clsmethod(cls):
print cls.var class SubClass(ParentClass): var = "test for sub"

此时ParentClass.clsmethod输出为 “test for parent”,而Subclass.clsmethod输出为“test for sub”,通过此比较很好的诠释了@classmethod类方法隐式传入的第一个参数是当前类,而不是父类。同时类方法操作的是class 类对象提供的内部信息。而staticmethod可以作为一般的工具函数来使用。

【练习】@property练习题的更多相关文章

  1. iOS:练习题中如何用技术去实现一个连线题

    一.介绍 本人做的app涉及的是教育行业,所以关于练习题的开发肯定是家常便饭.例如,选择题.填空题.连线题.判断题等,每一种题型都需要技术去实现,没啥多大难度,这里呢,就给出实现连线题的核心代码吧.过 ...

  2. FCC---Use the CSS Transform scale Property to Scale an Element on Hover

    The transform property has a variety of functions that let you scale, move, rotate, skew, etc., your ...

  3. 探究@property申明对象属性时copy与strong的区别

    一.问题来源 一直没有搞清楚NSString.NSArray.NSDictionary--属性描述关键字copy和strong的区别,看别人的项目中属性定义有的用copy,有的用strong.自己在开 ...

  4. JavaScript特性(attribute)、属性(property)和样式(style)

    最近在研读一本巨著<JavaScript忍者秘籍>,里面有一篇文章提到了这3个概念. 书中的源码可以在此下载.我将源码放到了线上,如果不想下载,可以直接访问在线网址,修改页面名就能访问到相 ...

  5. -Dmaven.multiModuleProjectDirectory system property is not set. Check $M2_HO 解决办法

    最近在使用maven,项目测试的时候出现了这么一个错.-Dmaven.multiModuleProjectDirectory system property is not set. Check $M2 ...

  6. python property理解

    一般情况下我这样使用property: @property def foo(self): return self._foo # 下面的两个decrator由@property创建 @foo.sette ...

  7. Android动画效果之Property Animation进阶(属性动画)

    前言: 前面初步认识了Android的Property Animation(属性动画)Android动画效果之初识Property Animation(属性动画)(三),并且利用属性动画简单了补间动画 ...

  8. Android动画效果之初识Property Animation(属性动画)

    前言: 前面两篇介绍了Android的Tween Animation(补间动画) Android动画效果之Tween Animation(补间动画).Frame Animation(逐帧动画)Andr ...

  9. # ios开发 @property 和 Ivar 的区别

    ios开发 @property 和 Ivar 的区别 @property 属性其实是对成员变量的一种封装.我们先大概这样理解: @property = Ivar + setter + getter I ...

随机推荐

  1. python if __name__=='__main__'的理解

    定义一个模块叫module.py: def main(): print "we are in %s" %__name__ if __name__=='__main__': main ...

  2. Oracle数据库表解锁语句

    --表解锁select sess.sid, sess.serial#, lo.oracle_username, lo.os_user_name, ao.object_name, lo.locked_m ...

  3. 《JavaScript Dom 编程艺术》读书笔记-第7章

    动态创建标记~内容包括: 1. 传统技术:document.write 和innerHTML 2. 深入剖析DOM方法:createElemen.createTextNode.appendChild和 ...

  4. copy GC 和 mark & compaction GC的算法异同

    先标记 然后 copy GC是,对所有child,判断, 如果child没有被访问过,那么拷贝到新地址,child的forwording指向新地址,child标记为已访问,把自己对child的引用改为 ...

  5. js带“.”的对象属性名怎么使用

    问题:这样的json对象(event) { "title": "title", "alert":"ding", &quo ...

  6. Vxlan基础理解

    一 . 为什么需要Vxlan   1. vlan的数量限制    4096个vlan远不能满足大规模云计算数据中心的需求   2. 物理网络基础设施的限制    基于IP子网的区域划分限制了需要二层网 ...

  7. Java notepad++ 配置

    1.下载安装插件 NppExec https://nchc.dl.sourceforge.net/project/npp-plugins/NppExec/NppExec%20Plugin%20v0.6 ...

  8. 2--Postman脚本介绍

    Postman是访问各种API的客户端.它的强大之处在于其允许在对某一个request访问的之前和之后分别运行自定义的一段Javascript脚本,可以将数条request连结成一个流程完成一体化测试 ...

  9. 03_安装vsftp服务器

    1 安装vsftpd组件 [root@bogon ~]# yum -y install vsftpd 安装完后,有/etc/vsftpd/vsftpd.conf 文件,是vsftp的配置文件. 2 添 ...

  10. s21day11 python笔记

    s21day11 python笔记 一.函数小高级 函数名可以当作变量来使用 #示例一: def func(): print(123) func_list = [func, func, func] # ...