Skip to content

Instantly share code, notes, and snippets.

@hanjae-jea
Last active December 5, 2018 00:11
Show Gist options
  • Save hanjae-jea/f55ae57e4b043b9f2fe3e1c349ee098d to your computer and use it in GitHub Desktop.
Save hanjae-jea/f55ae57e4b043b9f2fe3e1c349ee098d to your computer and use it in GitHub Desktop.
Blog
class A():
attr = "Cls attr"
instance1 = A()
instance2 = A()
print("I1 attr", instance1.attr)
instance2.attr = "New Attr"
print("I2 attr", instance2.attr)
print("I1 attr", instance1.attr)
A.attr = "New Cls"
print("I1 attr", instance1.attr)
class A():
attr = "Cls Attr"
def __init__(self):
self.item = "instance item"
self._initiate = True
def __setattr__(self, key, value):
print('setattr ', key, ' : ', value)
if hasattr(self, key) or \
not hasattr(self, '_initiate') or \
self._initiate is False:
object.__setattr__(self, key, value)
else:
print("Attirbute Error {}".format(key))
instance1 = A()
instance1.item = "this item"
instance1.sth = "what?"
instance1.attr = "wooow"
class A():
attr = "Cls Attr"
def __init__(self):
self.item = "instance item"
self._initiate = True
def __setattr__(self, key, value):
print('setattr ', key, ' : ', value)
if key in self.__dict__ or \
'_initiate' not in self.__dict__ or \
self._initiate is False:
object.__setattr__(self, key, value)
else:
print("Attirbute Error {}".format(key))
instance1 = A()
instance1.item = "this item"
instance1.sth = "what?"
instance1.attr = "wooow"
class Freeze:
def __setattr__(self, key, value):
if key in self.__dict__ or \
'_frozen' not in self.__dict__ or \
self._frozen is False:
object.__setattr__(self, key, value)
else:
print("Attribute Error {}".format(key))
def _freeze(self):
self._frozen = True
class A(Freeze):
attr = "Cls Attr"
def __init__(self):
self.item = "instance item"
self._freeze()
instance1 = A()
instance1.item = "this item"
instance1.sth = "what?"
instance1.attr = "wooow"
from functools import reduce
class Freeze:
def __setattr__(self, key, value):
if key in self.__dict__ or \
'_frozen' not in self.__dict__ or \
self._frozen is False:
object.__setattr__(self, key, value)
return
def rec(c, k):
return c if k in c.__dict__ else \
(reduce(lambda x, y: x or y, list(map(lambda x: rec(x, k), c.__bases__)), None))
cls = rec(self.__class__, key)
if cls is not None:
setattr(cls, key, value)
return
print("Attribute Error {}".format(key))
def _freeze(self):
self._frozen = True
class A(Freeze):
attr = "Cls Attr"
def __init__(self):
self.item = "instance item"
self._freeze()
class B(A):
bttr = "weeew"
def __init__(self):
self.btem = "b item"
super().__init__()
instance1 = B()
instance1.item = "this item"
instance1.sth = "what?"
instance1.attr = "wooow"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment