手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python的属性(property)使用

[日期:2017-12-18] 来源:Linux社区  作者:wxshi [字体: ]

在面向对象编程的时候,我们定义一个Person

class Person:
  def __init__(self):
      self.age = 22

这样写法能够方便的访问属性age,

p = Person()
print p.age ==>22
p.age = 30
print p.age ==>30

这样写起来虽然很简单,但是没有参数检验(eg,输入非数值,输入过大的数值)。
写过Java的人知道,在Java有一种类叫做实体类(entity,javabean等),它们一般不提供其他复杂的方法只提供简单的gettersetter等方法。如下例子

public class person{ 
private int age; 
 public String getAge()
{
     return this.age;
 } 
 public String setAge(String age)
{ 
    if(age > 100) {}//数值检验
     return this.age=age; 
 }
 }

同理我们可以按照这个思路来编写Python代码

class Person:
  def__init__(self):
      self.age = None
  def get_age(self):
      return self.age
  def set_age(self,age):
      if not isinstance(age, int):
            raise ValueError('age must be an integer!')
      if age < 0 or age > 100:
            raise ValueError('age must between 0 ~ 100!')
      self.age = age

这样写就完善很多,参数不会被随意更改了。访问age的时候需要使用p.get_age(),但这种写法不够pythonic,强大的python提供了@property方法,方法如下

class Person(object):
  def __init__(self):
      self._age = None
  @property
  def age(self):
      return self._age
  @age.setter
  def age(self,_age):
      if not isinstance(_age, int):
            raise ValueError('age must be an integer!')
      if _age < 0 or _age > 100:
            raise ValueError('age must between 0 ~ 100!')
      self._age = _age
p=Person()

这里面有一点需要注意,就是在自定义类的时候需要使用新式类,即继承了object

本文永久更新链接地址http://www.linuxidc.com/Linux/2017-12/149564.htm

linux
相关资讯       Python属性  Python property 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款