adding all files done so far
This commit is contained in:
18
learning/descriptors/descriptors.py
Normal file
18
learning/descriptors/descriptors.py
Normal file
@@ -0,0 +1,18 @@
|
||||
class Person(object):
|
||||
"""docstring for Person"""
|
||||
def __init__(self, name, age):
|
||||
super(Person, self).__init__()
|
||||
self.name = name
|
||||
self.age = age
|
||||
|
||||
@property
|
||||
def age(self):
|
||||
print('old enough')
|
||||
return self.__age
|
||||
|
||||
@age.setter
|
||||
def age(self, value):
|
||||
if value < 21:
|
||||
raise Exception(f'{self.name} is not old enough.')
|
||||
else:
|
||||
self.__age = value
|
||||
37
learning/descriptors/descriptors2.py
Normal file
37
learning/descriptors/descriptors2.py
Normal file
@@ -0,0 +1,37 @@
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
|
||||
class Drinker:
|
||||
def __init__(self):
|
||||
self.req_age = 21
|
||||
self.age = dict()
|
||||
print('init')
|
||||
|
||||
def __get__(self, instance_obj, objtype):
|
||||
print(f'{instance_obj}, {objtype}, {self.age}')
|
||||
return self.age.get(instance_obj, self.req_age)
|
||||
|
||||
def __set__(self, instance, new_age):
|
||||
if new_age < 21:
|
||||
msg = '{name} is too young to legally imbibe'
|
||||
raise Exception(msg.format(name=instance.name))
|
||||
self.age[instance] = new_age
|
||||
print('{name} can legally drink in the USA'.format(
|
||||
name=instance.name))
|
||||
|
||||
def __delete__(self, instance):
|
||||
del self.age[instance]
|
||||
|
||||
|
||||
class Person:
|
||||
drinker_age = Drinker()
|
||||
|
||||
def __init__(self, name, age):
|
||||
self.name = name
|
||||
self.drinker_age = age
|
||||
|
||||
|
||||
p = Person('Miguel', 30)
|
||||
p1 = Person('Bob', 50)
|
||||
|
||||
p = Person('Niki', 13)
|
||||
16
learning/descriptors/test.py
Normal file
16
learning/descriptors/test.py
Normal file
@@ -0,0 +1,16 @@
|
||||
class P(object):
|
||||
def __init__(self, x):
|
||||
self._x = x
|
||||
|
||||
@property
|
||||
def x(self):
|
||||
return self._x
|
||||
|
||||
@x.setter
|
||||
def x(self, x):
|
||||
if x < 0:
|
||||
self._x = 0
|
||||
elif x > 1000:
|
||||
self._x = 1000
|
||||
else:
|
||||
self._x = x
|
||||
Reference in New Issue
Block a user