【Python】 属性的 get 与 set 方法

在C#里面,属性的get 与 set 非常简单方便。

public class bird
{
	public  int age { get;set; }  
	public bool isadult
	{
		get {
			return this.age >= 1 ? true:false;
		}
	}
}

  

而在Python里面,属性可以直接获取或赋值。但是如果在获取或赋值时加一些逻辑判断,就稍微有点不一样。

class bird(object):

    def getAge(self):
        if age < 1 :return 1
        else : return age
    def setAge(self,value):
        if value > 2 : value = 2
        self.age = value
    age = property(getAge,setAge)

 

不过总的比起来要比java好多了(没错,我就是java黑)。

 

posted @ 2016-05-18 20:56  のんきネコ  阅读(8114)  评论(0编辑  收藏  举报