Added more test files from lectures.
This commit is contained in:
@@ -0,0 +1,52 @@
|
|||||||
|
class BoundedInt():
|
||||||
|
def __init__(self, i, min, max):
|
||||||
|
"""
|
||||||
|
Create a bounded integer.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
i (int): The initial value of the integer.
|
||||||
|
min (int): The minimum value of the integer.
|
||||||
|
max (int): The maximum value of the integer.
|
||||||
|
"""
|
||||||
|
self.i = i
|
||||||
|
if i < min or i > max:
|
||||||
|
raise ValueError(f"{i} is outside the range of [{min}, {max}].")
|
||||||
|
self.min = min
|
||||||
|
self.max = max
|
||||||
|
|
||||||
|
def __int__(self):
|
||||||
|
return self.i
|
||||||
|
|
||||||
|
def __index__(self):
|
||||||
|
return self.i
|
||||||
|
|
||||||
|
def __getattr__(self, name):
|
||||||
|
print(f"DEBUG: {type(name)=}, {name=}")
|
||||||
|
return lambda *args, **kwargs: None
|
||||||
|
|
||||||
|
def __add__(self, y):
|
||||||
|
if isinstance(y, BoundedInt):
|
||||||
|
i = y.i
|
||||||
|
else:
|
||||||
|
i = y
|
||||||
|
if self.i + i > self.max:
|
||||||
|
raise ValueError()
|
||||||
|
else:
|
||||||
|
return BoundedInt(self.i + i, self.min, self.max)
|
||||||
|
|
||||||
|
def __sub__(self, y):
|
||||||
|
if isinstance(y, BoundedInt):
|
||||||
|
i = y.i
|
||||||
|
else:
|
||||||
|
i = y
|
||||||
|
if self.i - i < self.min:
|
||||||
|
raise ValueError()
|
||||||
|
else:
|
||||||
|
return BoundedInt(self.i - i, self.min, self.max)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
b1 = BoundedInt(1,0,2)
|
||||||
|
b2 = BoundedInt(1,0,2)
|
||||||
|
print(f"{b1.doo}")
|
||||||
|
b3 = b1+b2
|
||||||
|
|
||||||
@@ -10,12 +10,6 @@ class TomatoPrice:
|
|||||||
def __radd__(self, operand):
|
def __radd__(self, operand):
|
||||||
self.price += operand.price
|
self.price += operand.price
|
||||||
|
|
||||||
b'abcdefg'
|
|
||||||
str = b.encode('UTF-8')
|
|
||||||
for c in str:
|
|
||||||
if ord(c) >= 32 and ord(c) < 127:
|
|
||||||
print(c)
|
|
||||||
|
|
||||||
vietnam = TomatoPrice(3.0)
|
vietnam = TomatoPrice(3.0)
|
||||||
japan = TomatoPrice(4.0)
|
japan = TomatoPrice(4.0)
|
||||||
korea = TomatoPrice(5.0)
|
korea = TomatoPrice(5.0)
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ class BoundedIntTester:
|
|||||||
Test that addition works for two BoundedInts, and throws an error if the bounds are exceeded.
|
Test that addition works for two BoundedInts, and throws an error if the bounds are exceeded.
|
||||||
"""
|
"""
|
||||||
bi4 = BoundedInt(1, min = 0, max = 1)
|
bi4 = BoundedInt(1, min = 0, max = 1)
|
||||||
bi5 = BoundedInt(2, min = 0, max = 2)
|
bi5 = BoundedInt(2, min = 0, max = -1)
|
||||||
try:
|
try:
|
||||||
bi6 = bi4 - bi5 # 1 - 2 = (-1), which is less than min = 0
|
bi6 = bi4 - bi5 # 1 - 2 = (-1), which is less than min = 0
|
||||||
print(f"❌ Test 3 failed!")
|
print(f"❌ Test 3 failed!")
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
class Test:
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def t1():
|
||||||
|
pass
|
||||||
|
|
||||||
|
def t2():
|
||||||
|
pass
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
t = Test()
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
class NotAdder:
|
||||||
|
def __init__(self):
|
||||||
|
self.i = 0
|
||||||
|
def __add__(self, other):
|
||||||
|
return NotImplemented
|
||||||
|
|
||||||
|
class Adder:
|
||||||
|
def __init__(self):
|
||||||
|
self.i = 1
|
||||||
|
def __add__(self, other: NotAdder):
|
||||||
|
return self.i + other.i
|
||||||
|
def __radd__(self, other: NotAdder):
|
||||||
|
return self.i + other.i
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
na = NotAdder()
|
||||||
|
a = Adder()
|
||||||
|
na + a
|
||||||
|
|
||||||
|
# if a + na => NotImplemented then
|
||||||
|
# na.__radd__(a)
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
class BoundedInt():
|
||||||
|
def __init__(self, i, min, max):
|
||||||
|
self.i = i
|
||||||
|
self.min = min
|
||||||
|
self.max = max
|
||||||
|
|
||||||
|
def __index__(self):
|
||||||
|
return self.i
|
||||||
|
|
||||||
|
def __add__(self, other):
|
||||||
|
if isinstance(other, BoundedInt):
|
||||||
|
result = self.i + other.i
|
||||||
|
elif isinstance(other, str):
|
||||||
|
score = sentiment(other)
|
||||||
|
result = self.i + score
|
||||||
|
else:
|
||||||
|
result = self.i + other
|
||||||
|
if result > self.max:
|
||||||
|
raise ValueError("Result exceeds max value")
|
||||||
|
return BoundedInt(result, self.min, self.max)
|
||||||
|
|
||||||
|
def __sub__(self, other):
|
||||||
|
if isinstance(other, BoundedInt):
|
||||||
|
result = self.i - other.i
|
||||||
|
elif isinstance(other, str):
|
||||||
|
score = sentiment(other)
|
||||||
|
result = self.i - score
|
||||||
|
else:
|
||||||
|
result = self.i - other
|
||||||
|
if result < self.min:
|
||||||
|
raise ValueError("Result exceeds min value")
|
||||||
|
return BoundedInt(result, self.min, self.max)
|
||||||
|
|
||||||
|
|
||||||
|
def sentiment(emoji):
|
||||||
|
sentiment_scores = {
|
||||||
|
"😀": 8.9,
|
||||||
|
"😢": -6.2,
|
||||||
|
"😡": -9.5,
|
||||||
|
"😍": 9.8,
|
||||||
|
}
|
||||||
|
return sentiment_scores.get(emoji, 0.0)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
b = BoundedInt(3, min = 0, max = 8)
|
||||||
|
b -= "😢"
|
||||||
|
|
||||||
|
#a = [1,2,3,4,5,6,7,8,9,10]
|
||||||
|
#print(f"{a[b]=}")
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
class Test:
|
||||||
|
a = [1,2,3,4,5]
|
||||||
|
|
||||||
|
a1 = 1
|
||||||
|
def __init__(self) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def sentiment(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __getattr__(self, str):
|
||||||
|
print(f"DEBUG: attempt to access attr {str}")
|
||||||
|
if int(str[1]) > 0 and int(str[1]) < 6:
|
||||||
|
return self.a[int(str[1])]
|
||||||
|
|
||||||
|
def c():
|
||||||
|
print(f"DEBUG: {c.__self__=}")
|
||||||
|
|
||||||
|
def i(self):
|
||||||
|
pass
|
||||||
|
#print(f"DEBUG: {i.__self__=}")
|
||||||
|
|
||||||
|
class ChildTest(Test):
|
||||||
|
pass
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
def whoami(who):
|
||||||
|
if isinstance(Test.c(), Test):
|
||||||
|
print("It's a Test!")
|
||||||
|
if isinstance(ChildTest.c(), ChildTest):
|
||||||
|
print("It's a ChildTest!")
|
||||||
|
|
||||||
|
test = Test()
|
||||||
|
childtest = ChildTest()
|
||||||
|
test.sentiment
|
||||||
|
whoami(test)
|
||||||
|
whoami(childtest)
|
||||||
|
print(f"{test.a1}")
|
||||||
|
print(f"{hasattr(test, 'sentiment')}")
|
||||||
|
|
||||||
|
print(f"{test.c=}")
|
||||||
|
print(f"{childtest.c=}")
|
||||||
|
test.i()
|
||||||
|
|
||||||
|
#print(test['1099'][2019][3])
|
||||||
|
#print(test.1099_2019_3)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
class C:
|
||||||
|
@classmethod
|
||||||
|
def class_method(cls):
|
||||||
|
print("Called class_method with cls:", cls)
|
||||||
|
|
||||||
|
def instance_method(self):
|
||||||
|
print("Called instance_method with self:", self)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def static_method():
|
||||||
|
print("Called static_method")
|
||||||
|
|
||||||
|
# Accessing class attributes
|
||||||
|
class_method_obj = C.__dict__["class_method"]
|
||||||
|
instance_method_obj = C.__dict__["instance_method"]
|
||||||
|
static_method_obj = C.__dict__["static_method"]
|
||||||
|
|
||||||
|
# Calling the methods directly (without transformation)
|
||||||
|
class_method_obj.__func__(C) # Output: Called class_method with cls: <class '__main__.C'>
|
||||||
|
instance_method_obj.__func__(1) # Output: Called instance_method with self: <__main__.C object at 0x7f8d7c1e4d90>
|
||||||
|
static_method_obj.__func__() # Output: Called static_method
|
||||||
|
|
||||||
|
# Accessing the methods through class attribute reference (with transformation)
|
||||||
|
C.class_method() # Output: Called class_method with cls: <class '__main__.C'>
|
||||||
|
C.instance_method(1) # Raises TypeError: instance_method() missing 1 required positional argument: 'self'
|
||||||
|
C.static_method() # Output: Called static_method
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
class Hotdog:
|
||||||
|
count: float = 0
|
||||||
|
def __init__(self) -> None:
|
||||||
|
Hotdog.count += 1
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_count() -> int:
|
||||||
|
return Hotdog.count
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
h1 = Hotdog()
|
||||||
|
print(Hotdog.get_count())
|
||||||
|
h2 = Hotdog()
|
||||||
|
print(Hotdog.get_count())
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
class Menu:
|
||||||
|
hotdog = 10
|
||||||
|
hamburger = 10
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.hotdog = 10
|
||||||
|
self.hamburger = 10
|
||||||
|
|
||||||
|
|
||||||
|
class SlotsMenu:
|
||||||
|
__slots__ = ('hotdog', 'hamburger', 'cheeseburger')
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.hotdog = 10
|
||||||
|
self.hamburger = 10
|
||||||
|
|
||||||
|
def __get__(self, instance):
|
||||||
|
print(f"DEBUG: looked up {instance}")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
menu = Menu()
|
||||||
|
|
||||||
|
print(f"cost of hamburger = {menu.hamburger}")
|
||||||
|
menu.__dict__['hamburger'] = 1
|
||||||
|
print(f"new cost of hamburger = {menu.hamburger}")
|
||||||
|
|
||||||
|
slotsmenu = SlotsMenu()
|
||||||
|
|
||||||
|
print(f"cost of hamburger = {slotsmenu.hamburger}")
|
||||||
|
slotsmenu.cheeseburger = 1
|
||||||
|
print(f"cost of cheeseburger: {slotsmenu.cheeseburger=}")
|
||||||
|
#slotsmenu.__dict__['hamburger'] = 1
|
||||||
|
print(f"new cost of hamburger = {slotsmenu.hamburger}")
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
from random import random
|
||||||
|
class EvilDescriptor:
|
||||||
|
i: int
|
||||||
|
|
||||||
|
def __init__(self, i) -> None:
|
||||||
|
self.i = i
|
||||||
|
|
||||||
|
def __set__(self, instance, i: int):
|
||||||
|
self.instance = i + (random()*10)-5
|
||||||
|
|
||||||
|
def __index__(self):
|
||||||
|
return int(self.i)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
evil = EvilDescriptor(3)
|
||||||
|
evil.i = 5
|
||||||
|
print(f"{int(evil)=}")
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
class Vault2:
|
||||||
|
def __init__(self):
|
||||||
|
self._treasure = "gold"
|
||||||
|
self._original_dict = dict(self.__dict__)
|
||||||
|
|
||||||
|
def __setattr__(self, name, value):
|
||||||
|
if name != "_treasure" and name in self.__dict__ and self._original_dict.get(name) != value:
|
||||||
|
print("attribute deleted!")
|
||||||
|
self.__dict__[name] = value
|
||||||
|
|
||||||
|
@property
|
||||||
|
def treasure(self):
|
||||||
|
if self.__dict__ != self._original_dict:
|
||||||
|
print("attribute deleted!")
|
||||||
|
return self._treasure
|
||||||
|
v = Vault2()
|
||||||
|
print(v.treasure)
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
class Vault:
|
||||||
|
def __init__(self):
|
||||||
|
self._treasure = 'gold'
|
||||||
|
self._original_attrs = self.__dict__.copy()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def treasure(self):
|
||||||
|
if self.__dict__ != self._original_attrs:
|
||||||
|
print('Attribute deleted!')
|
||||||
|
return self._treasure
|
||||||
|
def stuff(self):
|
||||||
|
...
|
||||||
|
|
||||||
|
def __setattr__(self, key, value):
|
||||||
|
self.__dict__[key] = value
|
||||||
|
if key != '_original_attrs' and hasattr(self, '_original_attrs') and self.__dict__ != self._original_attrs:
|
||||||
|
print('Attribute deleted!')
|
||||||
|
|
||||||
|
def __call__(self, *args):
|
||||||
|
print(f"attempt to call {args}")
|
||||||
|
|
||||||
|
v = Vault()
|
||||||
|
v(1,2,3)
|
||||||
Reference in New Issue
Block a user