From 0dd134860183a5a760dae6c4ee5514d97dd51178 Mon Sep 17 00:00:00 2001 From: cheezedoodle2 Date: Thu, 6 Apr 2023 17:03:21 -0700 Subject: [PATCH] Added more test files from lectures. --- BoundedInt.py | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ test11.py | 6 ------ test13.py | 2 +- test14.py | 12 ++++++++++++ test15.py | 21 +++++++++++++++++++++ test16.py | 49 ++++++++++++++++++++++++++++++++++++++++++++++++ test17.py | 46 +++++++++++++++++++++++++++++++++++++++++++++ test18.py | 26 ++++++++++++++++++++++++++ test19.py | 14 ++++++++++++++ test20.py | 33 ++++++++++++++++++++++++++++++++ test21.py | 17 +++++++++++++++++ test22.py | 17 +++++++++++++++++ test23.py | 23 +++++++++++++++++++++++ 13 files changed, 311 insertions(+), 7 deletions(-) create mode 100644 BoundedInt.py create mode 100644 test14.py create mode 100644 test15.py create mode 100644 test16.py create mode 100644 test17.py create mode 100644 test18.py create mode 100644 test19.py create mode 100644 test20.py create mode 100644 test21.py create mode 100644 test22.py create mode 100644 test23.py diff --git a/BoundedInt.py b/BoundedInt.py new file mode 100644 index 0000000..10ce704 --- /dev/null +++ b/BoundedInt.py @@ -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 + \ No newline at end of file diff --git a/test11.py b/test11.py index 3e536d2..30ff5f2 100644 --- a/test11.py +++ b/test11.py @@ -10,12 +10,6 @@ class TomatoPrice: def __radd__(self, operand): 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) japan = TomatoPrice(4.0) korea = TomatoPrice(5.0) diff --git a/test13.py b/test13.py index 13825f6..3c52452 100644 --- a/test13.py +++ b/test13.py @@ -28,7 +28,7 @@ class BoundedIntTester: Test that addition works for two BoundedInts, and throws an error if the bounds are exceeded. """ bi4 = BoundedInt(1, min = 0, max = 1) - bi5 = BoundedInt(2, min = 0, max = 2) + bi5 = BoundedInt(2, min = 0, max = -1) try: bi6 = bi4 - bi5 # 1 - 2 = (-1), which is less than min = 0 print(f"❌ Test 3 failed!") diff --git a/test14.py b/test14.py new file mode 100644 index 0000000..362df35 --- /dev/null +++ b/test14.py @@ -0,0 +1,12 @@ +class Test: + def __init__(self): + pass + + def t1(): + pass + + def t2(): + pass + +if __name__ == '__main__': + t = Test() \ No newline at end of file diff --git a/test15.py b/test15.py new file mode 100644 index 0000000..a5135fc --- /dev/null +++ b/test15.py @@ -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) \ No newline at end of file diff --git a/test16.py b/test16.py new file mode 100644 index 0000000..db57212 --- /dev/null +++ b/test16.py @@ -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]=}") \ No newline at end of file diff --git a/test17.py b/test17.py new file mode 100644 index 0000000..2ce71c5 --- /dev/null +++ b/test17.py @@ -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) \ No newline at end of file diff --git a/test18.py b/test18.py new file mode 100644 index 0000000..332d6b0 --- /dev/null +++ b/test18.py @@ -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: +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: +C.instance_method(1) # Raises TypeError: instance_method() missing 1 required positional argument: 'self' +C.static_method() # Output: Called static_method \ No newline at end of file diff --git a/test19.py b/test19.py new file mode 100644 index 0000000..699a96d --- /dev/null +++ b/test19.py @@ -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()) \ No newline at end of file diff --git a/test20.py b/test20.py new file mode 100644 index 0000000..0033851 --- /dev/null +++ b/test20.py @@ -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}") diff --git a/test21.py b/test21.py new file mode 100644 index 0000000..0be4ad6 --- /dev/null +++ b/test21.py @@ -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)=}") \ No newline at end of file diff --git a/test22.py b/test22.py new file mode 100644 index 0000000..4826c2a --- /dev/null +++ b/test22.py @@ -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) diff --git a/test23.py b/test23.py new file mode 100644 index 0000000..3cc69c3 --- /dev/null +++ b/test23.py @@ -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) \ No newline at end of file