diff --git a/Scott_Submissions/3.3_ReadingNote.md b/Scott_Submissions/3.3_ReadingNote.md new file mode 100644 index 0000000..9f74480 --- /dev/null +++ b/Scott_Submissions/3.3_ReadingNote.md @@ -0,0 +1,155 @@ +# 3.3 Reading Note + +They have same output: + +```Python +class MyClass: + def __getitem__(self, index): + return f"Item at index {index}" + +x = MyClass() +item = x[3] +print(item) # Output: Item at index 3 +``` +```Python +# Equivalent to type(x).__getitem__(x, 3) +item = type(x).__getitem__(x, 3) +print(item) # Output: Item at index 3 +``` + +--- +## 3.3.1 + +1. The object.__new__() method is a special method in Python that is called to create a new instance of a class. It is responsible for the low-level creation of an object before its initialization. + +2. The object.__init__() method is a special method in Python that is called after an instance of a class has been created by the __new__() method. It is responsible for initializing the object's attributes and performing any necessary setup. + +3. The object.__del__() method is a special method in Python that is called when an instance of a class is about to be destroyed or garbage-collected. + +4. The cyclic garbage collector in CPython is responsible for detecting and breaking reference cycles, ensuring that memory is properly deallocated even in the presence of reference cycles. + +5. the __format__() method allows objects to define their own customized string representations when used with format-related operations. + +6. x < y calls x.__lt__(y) + x <= y calls x.__le__(y) + x == y calls x.__eq__(y) + x != y calls x.__ne__(y) + x > y calls x.__gt__(y) + x >= y calls x.__ge__(y) + +--- +## 3.3.2 + +### 3.3.2.1 + +1. The methods __get__, __set__, and __delete__ are used to implement descriptors in Python. Descriptors are a way to customize attribute access in classes. These methods are defined in a descriptor class, and when an instance of the descriptor class is present in an owner class, they are invoked to control attribute access. + +### 3.3.2.2 +1. In Python, a descriptor is an object attribute that has "binding behavior" due to the overriding of attribute access through methods in the descriptor protocol: __get__(), __set__(), and __delete__(). If an object defines any of these methods, it is considered a descriptor. + +### 3.3.2.4 +1. Using __slots__ can save significant memory compared to using __dict__, and it can also improve attribute lookup speed. + +--- +## 3.3.3 +1. +``` Python +class Philosopher: + def __init_subclass__(cls, /, default_name, **kwargs): + super().__init_subclass__(**kwargs) + cls.default_name = default_name + +class AustralianPhilosopher(Philosopher, default_name="Bruce"): + pass +``` + +This code sets up a base class called Philosopher that defines a custom behavior for its subclasses when they are created. + +The default_name parameter allows each subclass to have a default name attribute, and the AustralianPhilosopher subclass demonstrates the usage by setting its default_name to "Bruce". + +1. The purpose of __set_name__() is to provide a hook for objects to perform any necessary initialization or setup when they are assigned to a class attribute. It allows the objects to be aware of their assigned name within the class they belong to, which can be useful for various purposes such as introspection or customization. + +### 3.3.3.1 +1. The C3 linearization algorithm is a method used to determine the order in which base classes are searched for a particular attribute or method during multiple inheritance in Python. It ensures that the resolution order respects the consistency and priority of the inheritance hierarchy. + +### 3.3.3.2 +1. MRO (Method Resolution Order) entries are resolved: This refers to the determination of the order in which base classes are searched for a particular attribute or method. The MRO defines the inheritance hierarchy and is calculated using the C3 linearization algorithm. + +--- +## 3.3.5 +1. Type annotations in Python refer to the practice of adding hints or metadata about the types of variables, function parameters, and return values in code. They are used to provide static type checking and improve code clarity, maintainability, and tooling support. They are optional and do not affect the runtime behavior of the code. Python remains a dynamically typed language, but type annotations allow developers to specify the expected types and enable type checking tools to catch potential errors. + +``` Python +x: int = 5 +def add(a: int, b: int) -> int: + return a + b +``` + +### 3.3.5.1 +1. The purpose of __class_getitem__() is to allow runtime parameterization of standard-library generic classes in order to more easily apply type hints to these classes. + +The __class_getitem__() method is called when you use square brackets notation ([]) with a generic class to specify the type arguments. For example: + +```Python +from typing import List + +# Define a generic class +class MyGenericClass: + ... + +# Use the generic class with type arguments +my_instance = MyGenericClass[int]() +``` + +In Python, generic classes are classes that can operate on different types of objects or collections in a flexible way. They are typically defined with type variables that represent the types of the objects or collections they work with. However, when using these generic classes, you need a way to specify the actual types you want to use. + +In the example above, 'MyGenericClass[int]()' invokes the __class_getitem__() method of MyGenericClass to specify that the type argument for the generic class is int. This allows you to parameterize the generic class at runtime and apply type hints to it. + +By implementing __class_getitem__() in your custom classes, you can enable similar behavior and allow runtime parameterization of your own generic classes. + +2. What is the runtime parameterization? + + **Runtime parameterization** refers to the ability to provide or specify parameters or arguments at runtime, rather than at compile time. It allows for dynamic customization or configuration of a program or component during its execution. + + In the context of generic classes in Python, **runtime parameterization** refers to the ability to specify type arguments or type parameters for a generic class at runtime. Generic classes are designed to work with different types of objects or collections in a flexible way, and the specific types they operate on can be determined dynamically. + + By allowing **runtime parameterization** of generic classes, you can provide the actual types or type arguments to be used when creating instances of the generic class. This enables you to customize the behavior or functionality of the generic class based on the specific types you need to work with in a particular situation. + + **Runtime parameterization** of generic classes is commonly used in scenarios where the types involved may vary or depend on external factors. It provides flexibility and adaptability to handle different data types or collections dynamically, without requiring explicit type annotations or definitions at compile time. + +--- +## 3.3.9 + +In this example, we define a 'FileManager' class that acts as a context manager for working with files. + +```Python +class FileManager: + def __init__(self, filename): + self.filename = filename + + def __enter__(self): + self.file = open(self.filename, 'w') + return self.file + + def __exit__(self, exc_type, exc_value, traceback): + self.file.close() + +# Usage of the context manager +with FileManager('example.txt') as file: + file.write('Hello, world!') +``` + 1. The *'__enter__'* method is responsible for setting up the runtime context, which in this case involves opening the specified file in write mode. The method returns the file object, which is then bound to the variable *'file'* in the *'with'* statement. + + 2. The *'__exit__'* method is called when exiting the runtime context. It is responsible for cleaning up any resources, in this case, closing the file. If an exception occurred within the *'with'* block, the exception information is passed to the *'__exit__'* method, allowing you to handle any necessary cleanup or error handling. + + 3. By using the *'with'* statement, the context manager automatically takes care of opening and closing the file for us. This ensures that the file is always closed, even if an exception occurs within the *'with'* block. + + 4. An explanation of the parameters in the *'__exit__'* method: + + **self**: The self parameter refers to the instance of the class itself. It allows you to access the attributes and methods of the class within the '__exit__' method. + + **exc_type**: This parameter represents the type of exception that occurred, if any. It will be None if no exception occurred within the with block. + + **exc_value**: This parameter holds the instance of the exception that occurred, if any. Like exc_type, it will be None if no exception occurred. + + **traceback**: The traceback parameter is a traceback object that encapsulates the call stack at the point where the exception occurred. It provides information about the line numbers and file names leading up to the exception. \ No newline at end of file diff --git a/Scott_Submissions/HW8.py b/Scott_Submissions/HW8.py new file mode 100644 index 0000000..e3b94c8 --- /dev/null +++ b/Scott_Submissions/HW8.py @@ -0,0 +1,85 @@ +# Create a class that implements a context manager as described in 3.3.9. +# The context manager should keep track of an array of banana emojis. +# The class should be able to be used with with: so it adds a banana to the list, and upon exit, removes a banana from the list. + +# class BananaManager: +# def __init__(self, bananas): +# self.bananas = bananas + +# def __enter__(self): +# self.bananas.append("🍌") +# return self.bananas + +# def __exit__(self, exc_type, exc_value, traceback): +# self.bananas.pop() + +# # Usage of the banana manager +# banana_list = ["🍌", "🍌"] +# print("Before with statement:", banana_list) + +# with BananaManager(banana_list) as adding_bananas: +# print("Inside with statement:", adding_bananas) + +# print("After with statement:", banana_list) + + + +# Questions: can you use a with block inside of another with block? (You might have to get creative for this to work.). +# If you can make that work, how many bananas are in the list? + +# class BananaManager: +# def __init__(self, bananas): +# self.bananas = bananas + +# def __enter__(self): +# self.bananas.append("🍌") +# return self.bananas + +# def __exit__(self, exc_type, exc_value, traceback): +# self.bananas.pop() + +# # Usage of the banana manager +# banana_list = ["🍌", "🍌"] +# print("Before with statement:", banana_list) + +# with BananaManager(banana_list) as adding_bananas: +# print("Inside first with statement:", adding_bananas) + +# with BananaManager(adding_bananas) as inside_bananas: +# print("Inside second with statement:", inside_bananas) + +# print("After with statement:", banana_list) + + + +# Another question: can you structure the program so that you can get the class to have more than 0 bananas *outside* of a with block? + +class BananaManager: + def __init__(self, bananas): + self.bananas = bananas + + def __enter__(self): + self.bananas.append("🍌") + return self.bananas + + def __exit__(self, exc_type, exc_value, traceback): + self.bananas.pop() + + def outside_banana(self): + self.bananas.append("🍌") + +# Usage of the banana manager +banana_list = ["🍌", "🍌"] +print("Before with statement:", banana_list) + +bananamanager = BananaManager(banana_list) +bananamanager.outside_banana() # Add a banana outside of a with block +print("Outside adding a banana:", banana_list) + +with BananaManager(banana_list) as adding_bananas: + print("Inside first with statement:", adding_bananas) + + with BananaManager(adding_bananas) as inside_bananas: + print("Inside second with statement:", inside_bananas) + +print("After with statement:", banana_list)