3 - Python
ucla | CS 131 | 2023-10-18 14:41
Table of Contents
- Variables
- Classes
- Copying
- Garbage collection
- Inheritance
- Objects
- Parameter Passing
- Error Handling
- Multi-Threading
- Comprehensions
Variables
- only makes
__name__
var whenmain()
present to call__name__==__main__
- variables have scope within functions, not within conditional blocks
- double underscore to make member functions private
- ALL data is object references, and all of it is stored in a heap - inefficient
- data on the heap is immutable, instead, it creates a new object and references that and garbage collects the old
- data allocation size is managed by a dictionary that determines the size
Classes
- class variables/objects (non self, just defined at the top of the class) are accessible by all objects of that class
- class methods have no
self
param and cannot access class member variables - copying is by default soft copy and creates object references
- use
copy.deepcopy
does a recursive, depth-first copy of the actual object, not just the reference - shallow copy (
copy.copy
) only copies the top level object (not recursive) i.e. in the example the pointers in thee array point to the same values as the other array - garbage collection is automatic
- destructor defined using
__del__
but not guaranteed to run and rarely used - finalizer runs before the garbage collector to finalize anything with that object, then garbage collects i.e. destructor but is being phased out
- instead, define your own disposal method to dispose
Inheritance
Objects
Object Equality
None
- acts like a
nullptr
Strings
- Strings are immutable, just like all other objects
- treated as a list of chars, so use list indexing to access substrings
Lists - MIDTERM
- lists ARE mutable
-
a.append(b)
==a+=b
!=a = a+b
- List implementation: array of object references
Tuples
- immutable ordered groups
Sets
- Stores a single unique copy
- not ordered alphabetically
- implemented using hash tables
- sets have simple, built in set operations
Parameter Passing
- by object reference
Error Handling
- called exceptions
- python provides a stack traceback to track where the error came from
- use try/except block to handle exceptions
- you can except for all or per error or as some variable
e
- Python starts the first thread and it gains exclusive access to the objects
- instead, Python has a GIL (Global Interpreter Lock) i.e., a mutex (lock), so each thread releases the GIL when its done with it access
- instead, multi-threading is for non-computational, e.g. I/O (Reading/writing from disk) and libraries where they are written in C/C++