Python Advanced
Summary Table
Summary of the Python Advanced section.
Concept | Example | Description |
---|---|---|
Basic function | def my_function(): |
Define a reusable block of code |
Parameters | def my_function(param): |
Input values to the function |
Return values | return value |
Send a result back to the caller |
Default values | def my_function(param="default"): |
Provide fallback values for parameters |
Keyword arguments | my_function(arg2="value", arg1="val") |
Pass arguments by name |
*args |
def my_function(*args): |
Handle multiple positional arguments |
**kwargs |
def my_function(**kwargs): |
Handle multiple named keyword arguments |
Multiple return values | return val1, val2 |
Return several values as a tuple |
Class definition | class MyClass: |
Blueprint for creating objects |
Object creation | obj = MyClass() |
Instantiate an object from a class |
__init__ method |
def __init__(self, ...) |
Set up initial object state |
Attributes | self.attribute |
Store data in the object |
Methods | def my_method(self): |
Function that operates on object data |
self keyword |
self.value = value |
Refers to the current instance of the class |
Class vs. instance attr | MyClass.attr , self.attr |
Shared by all objects vs. unique per instance |
Inheritance | class SubClass(SuperClass): |
Derive one class from another |
super() |
super().__init__(...) |
Call a method from the parent class |
Object identity | obj1 == obj2 |
Compare references vs. internal values |
Basic import | import module |
Load an entire module |
Import specific parts | from module import item1, item2 |
Bring in only selected functions, classes, etc. |
Aliasing | import module as alias |
Rename a module or function for convenience |
Aliased import (partial) | from module import item as alias |
Rename a specific item during import |
Wildcard import | from module import * |
Import everything from a module (not recommended) |
Custom module import | import mymodule |
Import your own Python files as modules |
Conditional import | if condition: import module |
Load a module only when needed |
Import error | import nonexistent |
Happens when module or item is not found |