1. 程式人生 > >python3 property用法

python3 property用法

1,當私有屬性無法訪問時需要設定set get方法來在外部使用它

class Test(object):
    def __init__(self):
        self.__num = 0

    def setnum(self,newnum):
        if isinstance(newnum,int):
            num=newnum
        else:
            print('newnum not int')

    def getnum(self):
        return self.__num

2,可以使用property方法將get 和 set轉化成可訪問的屬性

class Test(object):
    def __init__(self):
        self.__num = 0

    def setnum(self, newnum):
        print("i am set")
        if isinstance(newnum,int):
            self.__num = newnum
        else:
            print('newnum not int')

    def getnum(self):
        print("i am get")
        return self.__num
    num = property(getnum,setnum)
t = Test()
print(t.num)
print('-'*50)
t.num = 2
print(t.num)

3,使用property替代set 與get方法

class Test(object):
    def __init__(self):
        self.__num = 0
    @property
    def num(self):
        print("i am get")
        return self.__num
    @num.setter
    def num(self, newnum):
        print("i am set")
        if isinstance(newnum, int):
            self.__num = newnum
        else:
            print('newnum not int')

t = Test()
print(t.num)
print('-'*50)
t.num = 2
print(t.num)