美文网首页
Python Property 属性

Python Property 属性

作者: 一本大书 | 来源:发表于2018-11-08 17:47 被阅读13次
class Test(object): 
    def __init__(self):
        super(Test, self).__init__()

    def getNum(self):
            print("-get")
            return self.__num

    def setNum(self, newNum):
        print("-set")
        self.__num = newNum

    num = property(getNum, setNum)


test = Test()
test.num = 20
print(test.num)

输出结果:

-set
-get
20

更加简介的方式如下:

class Test(object): 
    def __init__(self):
        super(Test, self).__init__()

    @property
    def num(self):
        print("-get")
        return self.__num   

    @num.setter
    def num(self, value):
        print("-set")
        self.__num = value 

test = Test()
test.num = 20 
print(test.num)

相关文章

  • python @property

    参考 Python进阶之“属性(property)”详解 - Python - 伯乐在线

  • 属性Property

    property也是一个类,@property成为属性函数,即可以将python定义的方法当做属性访问,可以对属性...

  • Python Property 属性

    输出结果: 更加简介的方式如下:

  • python属性property

    属性函数(property)在对象中两个很重要的元素就是属性和方法,在调用的时候两者是有区别的。 从例子中我们可以...

  • Python: property属性

    @property可以把一个实例方法变成其同名属性,以支持.号访问@property属性的两种方式装饰器:在方法上...

  • python 属性property

    class Person:def init(self, first_name):self.first_name =...

  • 属性property

    Python中有一个被称为属性函数(property)的小概念,它可以做一些有用的事情。属性property能做以...

  • Python 描述符对象 Descriptor Objects

    Reproduce from python描述符(descriptor)、属性(Property)、函数(类)装饰...

  • python练习7_@property的使用

    首先理解@property:@property是将python定义的函数"当做"属性来访问,从而提供更加友好的访问...

  • Python 扩展property属性

    我们都知道property是将类的方法变成属性的装饰器 有时候我们想隐藏一些内部的属性,不让外部可以调用和更改。我...

网友评论

      本文标题:Python Property 属性

      本文链接:https://www.haomeiwen.com/subject/plawxqtx.html