diff --git a/README.md b/README.md index fccab07..66ac9b8 100644 --- a/README.md +++ b/README.md @@ -816,6 +816,8 @@ player = Player(point, direction) # Returns its instance. Imports ------- +**Mechanism that makes code in one module available to another module.** + ```python import # Imports a built-in or '.py'. import # Imports a built-in or '/__init__.py'. @@ -826,7 +828,6 @@ import . # Imports a built-in or '/.py'. * **Running `'import '` does not automatically provide access to the package's modules unless they are explicitly imported in its init script.** * **Location of the file that is passed to python command serves as a root of all local imports.** * **For relative imports use `'from .[…][[.…]] import '`.** -* **To install your package go to its parent dir, add 'import setuptools; setuptools.setup()' to setup.py, '[options]' and 'packages = <dir>' to setup.cfg, and run `'pip3 install -e .'`.** Closure @@ -951,8 +952,10 @@ def add(x, y): Class ----- +**A template for creating user-defined objects.** + ```python -class : +class MyClass: def __init__(self, a): self.a = a def __str__(self): @@ -969,6 +972,12 @@ class : * **If only repr() is defined, it will also be used for str().** * **Methods decorated with `'@staticmethod'` do not receive 'self' nor 'cls' as their first arg.** +```python +>>> obj = MyClass(1) +>>> obj.a, str(obj), repr(obj) +(1, '1', 'MyClass(1)') +``` + #### Expressions that call the str() method: ```python print() @@ -987,13 +996,6 @@ Z = dataclasses.make_dataclass('Z', ['a']); print/str/repr(Z()) >>> ``` -### Constructor Overloading -```python -class : - def __init__(self, a=None): - self.a = a -``` - ### Inheritance ```python class Person: @@ -1006,7 +1008,7 @@ class Employee(Person): self.staff_num = staff_num ``` -### Multiple Inheritance +#### Multiple inheritance: ```python class A: pass class B: pass @@ -1019,26 +1021,6 @@ class C(A, B): pass [, , , ] ``` -### Property -**Pythonic way of implementing getters and setters.** -```python -class Person: - @property - def name(self): - return ' '.join(self._name) - - @name.setter - def name(self, value): - self._name = value.split() -``` - -```python ->>> person = Person() ->>> person.name = '\t Guido van Rossum \n' ->>> person.name -'Guido van Rossum' -``` - ### Type Annotations * **They add type hints to variables, arguments and functions (`'def f() -> :'`).** * **Hints are used by type checkers like [mypy](https://pypi.org/project/mypy/), data validation libraries such as [Pydantic](https://pypi.org/project/pydantic/) and lately also by [Cython](https://pypi.org/project/Cython/) compiler. However, they are not enforced by CPython interpreter.** @@ -1072,6 +1054,26 @@ class : = ('', [, ]) ``` +### Property +**Pythonic way of implementing getters and setters.** +```python +class Person: + @property + def name(self): + return ' '.join(self._name) + + @name.setter + def name(self, value): + self._name = value.split() +``` + +```python +>>> person = Person() +>>> person.name = '\t Guido van Rossum \n' +>>> person.name +'Guido van Rossum' +``` + ### Slots **Mechanism that restricts objects to attributes listed in 'slots', reduces their memory footprint.** diff --git a/index.html b/index.html index 31dc56e..05177db 100644 --- a/index.html +++ b/index.html @@ -684,18 +684,18 @@ direction = Direction.N # Player = make_dataclass('Player', ['loc', 'dir']) # Creates a class. player = Player(point, direction) # Returns its instance. -

#Imports

import <module>            # Imports a built-in or '<module>.py'.
+

#Imports

Mechanism that makes code in one module available to another module.

import <module>            # Imports a built-in or '<module>.py'.
 import <package>           # Imports a built-in or '<package>/__init__.py'.
 import <package>.<module>  # Imports a built-in or '<package>/<module>.py'.
 
+
  • Package is a collection of modules, but it can also define its own objects.
  • On a filesystem this corresponds to a directory of Python files with an optional init script.
  • Running 'import <package>' does not automatically provide access to the package's modules unless they are explicitly imported in its init script.
  • Location of the file that is passed to python command serves as a root of all local imports.
  • For relative imports use 'from .[…][<pkg/module>[.…]] import <obj>'.
  • -
  • To install your package go to its parent dir, add 'import setuptools; setuptools.setup()' to setup.py, '[options]' and 'packages = <dir>' to setup.cfg, and run 'pip3 install -e .'.

#Closure

We have/get a closure in Python when a nested function references a value of its enclosing function and then the enclosing function returns the nested function.

def get_multiplier(a):
     def out(b):
@@ -800,7 +800,7 @@ player = Player(point, direction)                   #
 
  • Using only '@debug' to decorate the add() function would not work here, because debug would then receive the add() function as a 'print_result' argument. Decorators can however manually check if the argument they received is a function and act accordingly.
-

#Class

class <name>:
+

#Class

A template for creating user-defined objects.

class MyClass:
     def __init__(self, a):
         self.a = a
     def __str__(self):
@@ -814,11 +814,16 @@ player = Player(point, direction)                   #
         return cls.__name__
 
+
  • Return value of repr() should be unambiguous and of str() readable.
  • If only repr() is defined, it will also be used for str().
  • Methods decorated with '@staticmethod' do not receive 'self' nor 'cls' as their first arg.
+
>>> obj = MyClass(1)
+>>> obj.a, str(obj), repr(obj)
+(1, '1', 'MyClass(1)')
+

Expressions that call the str() method:

print(<el>)
 f'{<el>}'
 logging.warning(<el>)
@@ -833,11 +838,6 @@ Z = dataclasses.make_dataclass('Z', [>>> <el>
 
-

Constructor Overloading

class <name>:
-    def __init__(self, a=None):
-        self.a = a
-
-

Inheritance

class Person:
     def __init__(self, name):
         self.name = name
@@ -848,7 +848,7 @@ Z = dataclasses.make_dataclass('Z', [
-

Multiple Inheritance

class A: pass
+

Multiple inheritance:

class A: pass
 class B: pass
 class C(A, B): pass
 
@@ -857,22 +857,6 @@ Z = dataclasses.make_dataclass('Z', [>>> C.mro() [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
-

Property

Pythonic way of implementing getters and setters.

class Person:
-    @property
-    def name(self):
-        return ' '.join(self._name)
-
-    @name.setter
-    def name(self, value):
-        self._name = value.split()
-
- - -
>>> person = Person()
->>> person.name = '\t Guido  van Rossum \n'
->>> person.name
-'Guido van Rossum'
-

Type Annotations

  • They add type hints to variables, arguments and functions ('def f() -> <type>:').
  • Hints are used by type checkers like mypy, data validation libraries such as Pydantic and lately also by Cython compiler. However, they are not enforced by CPython interpreter.
  • @@ -903,6 +887,22 @@ Z = dataclasses.make_dataclass('Z', [<class> = make_dataclass('<class_name>', <coll_of_attribute_names>) <class> = make_dataclass('<class_name>', <coll_of_tuples>) <tuple> = ('<attr_name>', <type> [, <default_value>])
+

Property

Pythonic way of implementing getters and setters.

class Person:
+    @property
+    def name(self):
+        return ' '.join(self._name)
+
+    @name.setter
+    def name(self, value):
+        self._name = value.split()
+
+ + +
>>> person = Person()
+>>> person.name = '\t Guido  van Rossum \n'
+>>> person.name
+'Guido van Rossum'
+

Slots

Mechanism that restricts objects to attributes listed in 'slots', reduces their memory footprint.

class MyClassWithSlots:
     __slots__ = ['a']
     def __init__(self):