Skip to content

Instantly share code, notes, and snippets.

@leotrs
Created May 27, 2016 16:07
Show Gist options
  • Save leotrs/3bb8867bf34a028752ecf38c3d0f2e2a to your computer and use it in GitHub Desktop.
Save leotrs/3bb8867bf34a028752ecf38c3d0f2e2a to your computer and use it in GitHub Desktop.
# properties.py
# test python properties!
import math
class LittleThing():
def __init__(self, state):
self.state = state
class Thing():
def __init__(self, state):
self.children = [LittleThing(state) for i in range(5)]
# handles reading: Thing.state
@property
def state(self):
return any([c.state for c in self.children])
# handles writing: Thing.state = val
@state.setter
def state(self, val):
if not val:
for c in self.children:
c.state = False
else:
if not self.state:
self.children[0].state = True
def update(self, new_state):
self.state = new_state
if __name__ == "__main__":
t = Thing(True)
print("My state is: ", t.state)
for c in t.children:
c.state = False
print("My state is: ", t.state)
t.state = True
print("My state is: ", t.state)
print("My children: ", [c.state for c in t.children])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment