Skip to content

Instantly share code, notes, and snippets.

@cryptowen
Created February 21, 2017 15:30
Show Gist options
  • Save cryptowen/460a49792dc2c5351f7366c645f72637 to your computer and use it in GitHub Desktop.
Save cryptowen/460a49792dc2c5351f7366c645f72637 to your computer and use it in GitHub Desktop.
python property demo
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
zhihu question demo: https://www.zhihu.com/question/55594368
'''
class Mat(object):
"""动态读,class 内部只存 temp 的值,每次取 pro 的时候实时计算"""
def __init__(self, t):
self.temp = t
@property
def pro(self):
return self.temp * self.temp
a = Mat(5)
print(a.temp, a.pro) # (5, 25)
a.temp = 10
print(a.temp, a.pro) # (10, 100)
class Mat2(object):
"""两个都存,写入的时候两个都改"""
def __init__(self, t):
self.temp = t
@property
def temp(self):
return self._temp
@temp.setter
def temp(self, v):
self._temp = v
self.pro = self.Pro(v)
def Pro(self, t):
return t * t
a = Mat2(5)
print(a.temp, a.pro) # (5, 25)
a.temp = 10
print(a.temp, a.pro) # (10, 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment