Python面向对象@property用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haeasringnar/article/details/79964450
class Test_len():
    def __len__(self):  #这个方法可以使实例化后的对象被len()使用并返回自己想要的长度
        return 100
t = Test_len()
print(len(t))
'''
访问限制:私有属性,私有方法,类属性,实例属性,
双下划线意思是私有变量/私有属性,只有类对象自己可以访问。
'''
class Student():
    shcool = 'beijingdaxue'
    def __init__(self,name,score,age):
        self.name = name   #这个叫实例属性 也是普通属性
        self.__score = score  #这就是私有属性
        self._age = age
    def getscore(self):
        print(self.__score)
    def __getage(self):  #私有方法
        print(self._age)
    def getage(self):
        self.__getage()

s = Student('张三',99,24)
print(s.name)  #这是一个普通属性,可以随意查看并修改
# s.__score #这个时候就会报一个错误
s.getscore()
# print(s._age)  #发现实例对象依然可以访问
# s.__getage()
s.getage()
print(s.shcool)  #如果实例找不到实例属性时,就会去找类实型调用

'''
__slots__ 方法的使用
一般情况下我们可以任意的给实例添加方法和属性,但是有的时候我们想要限制允许的属性名称
这个时候就可以使用__slots__
'''
class MyStudent():
    pass
    # __slots__ = ('name','age','score')

ms = MyStudent()
ms.name = '123'
print(ms.name)
# ms.talk = 'i talk'  #发现这里会报错,因为我们没有允许这个属性可以被添加
# print(ms.talk)

def set_age(self,age):
    self.age = age
    print(self.age)
#动态给类添加方法
ms.set_age = set_age
ms.set_age(ms,25)  #这里返回的是实例本身

'''
@property 的使用
在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改:
这显然不合逻辑。为了限制score的范围,可以通过一个set_score()方法来设置成绩,
再通过一个get_score()来获取成绩,这样,在set_score()方法里,就可以检查参数:
'''

class Shcool():
    def get_score(self):
        return self._score
    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
ss = Shcool()
ss.set_score(66)
print(ss.get_score())

'''
更简单的方法就是使用@property  也被称为静态属性
@property的实现比较复杂,我们先考察如何使用。把一个getter方法变成属性,
只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,
'''

class TwoStudent(object):
    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value

    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self, value):
        self._birth = value

    @property
    def age(self):
        return 2015 - self._birth


    @property
    def width(self):
        return self.__width
    @width.setter
    def width(self,width):
        self.__width = width

    @property
    def height(self):
        return self.__height
    @height.setter
    def height(self, height):
        self.__height = height

    @property
    def resolution(self):
        return self.__width * self.__height

ts = TwoStudent()
ts.score = 83
print(ts.score)

ts.birth = 1995
print(ts.birth)
print(ts.age)
# ts.age = 10  #这个时候就发现age已经不可以被修改了,这里就隐藏了age属性,使得外部无法随意修改age

ts.width = 1024
ts.height = 768
print(ts.resolution)
阅读更多
换一批

[D]python编程property()用法

07-01

python 2.5版本:rnrn[code=Python]rn#这个版本无法正确运行rn__metaclass__ = typernrnclass rectangle :rnrn def __init__(self, arg_width=0, arg_height=0) :rn self.width = arg_widthrn self.height = arg_heightrnrn def setItem( self, *value ) : #可接受元祖参数值rn self.width, self.height = valuernrn def getItem(self) :rn return self.width, self.heightrnrn def delItem(self) :rn del self.widthrn del self.heightrnrn size = property(getItem,setItem,delItem, "display rectangle property")rnrn#这个版本可以通过size返回属性,但不能通过size设置属性:rn>>> rect = rectangle()rn>>> rect.width , rect.height = 10, 20rn>>> rect.sizern(10, 20)rn>>> rect.size(100,200) #通过size设置width ,height时rnrnTraceback (most recent call last):rn File "", line 1, in rn rect.size(100,200)rnTypeError: 'tuple' object is not callablern>>> rect.size = 100, 200 #通过size设置width ,height时rnrnTraceback (most recent call last):rn File "", line 1, in rn rect.size = 100, 200rn File "C:/Users/TOSHIBA/Desktop/TmpFile/PythonCode/property", line 10, in setItemrn self.width, self.height = valuernValueError: need more than 1 value to unpackrn>>> rect.size = (100,200) #通过size设置width ,height时rnrnTraceback (most recent call last):rn File "", line 1, in rn rect.size = (100,200)rn File "C:/Users/TOSHIBA/Desktop/TmpFile/PythonCode/property", line 10, in setItemrn self.width, self.height = valuernValueError: need more than 1 value to unpackrnrn[/code]rnrn[code=Python]rnrn#这个版本可以正确运行rnrn__metaclass__ = typernrnclass rectangle :rnrn def __init__(self, arg_width=0, arg_height=0) :rn self.width = arg_widthrn self.height = arg_heightrnrn def setItem( self, tuple ) : #显示定义可接受元祖参数rn self.width, self.height = tuplernrn def getItem(self) :rn return self.width, self.heightrnrn def delItem(self) :rn del self.widthrn del self.heightrnrn size = property(getItem,setItem,delItem, "display rectangle property")rnrn[/code]rnrn[code=Python]rn#这个是《python基础教程》(第2版) 上148页的例题,也无法正确运行rn__metaclass__ = typernrnclass rectangle :rnrn def __init__(self) :rn self.width = 0rn self.height = 0rnrn def setItem( self, value ) : rn self.width, self.height = valuernrn size = property(getItem,setItem)rnrn[/code]rnrn官方说明:rnrnproperty( [fget[, fset[, fdel[, doc]]]]) rnrnReturn a property attribute for new-style classes (classes that derive from object). rnfget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x: rnrnrn[code=Python]rnclass C(object):rn def __init__(self): self.__x = Nonern def getx(self): return self._xrn def setx(self, value): self._x = valuern def delx(self): del self._xrn x = property(getx, setx, delx, "I'm the 'x' property.")rn[/code]rnrnrnIf given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator: rnrn[code=Python]rnclass Parrot(object):rn def __init__(self):rn self._voltage = 100000rnrn @propertyrn def voltage(self):rn """Get the current voltage."""rn return self._voltagern[/code]rnrnturns the voltage() method into a ``getter'' for a read-only attribute with the same name. rnrnNew in version 2.2. Changed in version 2.5: Use fget's docstring if no doc given. rnrnrn谁给讲解下。thxrnrn---------------------------rnDouble行动:rn原帖分数:20rn帖子加分:20

没有更多推荐了,返回首页