请利用@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的super方法的用法理解

    参考链接:https://www.cnblogs.com/dkblog/archive/2011/02/24/1980654.html https://www.cnblogs.com/wjx1/p/5 ...

  2. Linux过滤错误日志

    grep -E 'at |Exception|exception|Error|error|Caused by' test.log

  3. SpringMvc开发报找不到springmvc配置文件

    param-name标签属性值必须为contextConfigLocation

  4. 周强 201771010141 《面向对象程序设计(java)》第七周学习总结

    实验目的与要求 (1)进一步理解4个成员访问权限修饰符的用途: (2)掌握Object类的常用API用法: (3)掌握ArrayList类用法与常用API: (4)掌握枚举类使用方法: (5)结合本章 ...

  5. element ui表格相同内容自动合并

    一开始觉得合并单元格很困难,什么鬼,后来仔细查看api,发现是可以实现的,特此记录下,直接看代码, 项目需求是第一列和第二列还有第16列需要相同内容进行合并,所以判断条件是不同的: 实现后效果如下: ...

  6. Ubuntu Server 16.04设置WiFi

    wifi :http://www.cnblogs.com/joeyupdo/p/3350463.html http://blog.csdn.net/meic51/article/details/173 ...

  7. 素数定理π(n)~n/lnn弱化版证明

    在大半年前写的Miller-Rabin素数测试正确性证明中使用过此结论~当时完全不会证,现在进步了一点点会证弱化版的了Orz 完整版的素数定理: π(n):=|{p|p<=n,p是素数}| li ...

  8. Windows文件夹、文件源代码对比工具--WinMerge

    /********************************************************************** * Windows文件夹.文件源代码对比工具--WinM ...

  9. C与指针练习题4.14.1

    //C与指针练习题4.14.1 //ai+1=(ai+n/ai)/2公式逼近,当ai+1=ai时,取得n的平方根 #include<stdio.h> float sq_root(float ...

  10. Json&xml分析~

    1.什么是Json? JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. 易于人阅读和编写.同时也易于机器解析和生成. 它基于JavaScript Prog ...