Code Monkey home page Code Monkey logo

learn-python's Introduction

Functional Python

Introduction

  • Origin of Python
  • Features
  • Limitations
  • Versions
  • Applications
  • Hello World
  • Interactive mode and script mode
  • Interpreter vs compilers

Basics

  • Modules

  • Statements

  • Character set

    1. A-Z
    2. a-z
    3. 0-9
    4. Underscore in Python.
  • Variables

  • Underscore

    1. For storing the value of last expression in interpreter.
    2. For ignoring the specific values. (so-called “I don’t care”)
    3. To give special meanings and functions to name of vartiables or functions.
    4. To use as ‘Internationalization(i18n)’ or ‘Localization(l10n)’ functions.
    5. To separate the digits of number literal value.
  • Constants

  • comments

    1. single line
    2. multiline
  • Code blocks and Indentation

    1. pass
  • Comments


Tokens

  • Keywords (35)
    1. Difference between del and None:
    2. async and await - python 3.7
  • Identifiers
  • Literals
    1. Int literals
    2. String literals
  • Punctuators
  • Operators
    1. Arithmetic Operators

      1. + ==>Addition
      2. - ==>Subtraction
      3. * ==>Multiplication
      4. / ==>Division operator
      5. % ===>Modulo operator
      6. // ==>Floor Division operator
      7. ** ==>Exponent operator or power operator
    2. Relational Operators or Comparison Operators

      • >
      • <
      • >=
      • >=
      • ==
      • !=
    3. Equality operators

      • ==
      • !=
      • Chaining
    4. Logical operators

      • and
      • or
      • not
      • Boolean types behaviour
        1. and ==>If both arguments are True then only result is True
        2. or ====>If atleast one arugemnt is True then result is True
        3. not ==>complement
        4. True and False ==>False
        5. True or False ===>True
        6. not False ==>True
      • Non boolean types behaviour
        1. x and y:
          1. if x is evaluates to false return x otherwise return y
        2. x or y:
          1. If x evaluates to True then result is x otherwise result is y
    5. Bitwise oeprators

      • &
      • |
      • ^
      • ~
      • <<
      • >>
    6. Assignment operators

      • =
      • Augmented Assignments
        • +=
        • -=
        • *=
        • /=
        • //=
        • **=
    7. Ternary operators

    8. Special operators

      1. Identity Operators
        1. is
        2. is not
      2. Membership operators
        1. in
        2. not in
    9. Walrus operator

      • ->
  • Operator precedence

Data types

• Type checking

Integer Types 1. int 1. Literals 1. Binary 1. Octals 1. Hexadecimals 1. float 1. complex

• None Type

• Boolean Type

Sequence Types

  1. str

    1. literals
      1. single line
      2. multiline
    2. Raw strings
    3. Operations
      1. Accessing
      2. Indexing
      3. Slicing
    4. Operators for string
      1. + operator for concatenation
      2. * operator for repetition
      3. <,<=,>,>= Comparison
      4. ==,!= equality
      5. in , not in membership
    5. Formatting 1. Formatted string 1. %i - int 1. %d - int 1. %f - float 1. %s - String type 1. %r - 1. print with {} operator
    6. Escape Sequenses
      • \a ASCII Bell (BEL) character
      • \b ASCII Backspace (BS) character
      • \f ASCII Formfeed (FF) character
      • \n ASCII Linefeed (LF) character
      • \N{} Character from Unicode database with given
      • \r ASCII Carriage Return (CR) character
      • \t ASCII Horizontal Tab (TAB) character
      • \uxxxx Unicode character with 16-bit hex value xxxx
      • \Uxxxxxxxx Unicode character with 32-bit hex value xxxxxxxx
      • \v ASCII Vertical Tab (VT) character
      • \oxx Character with octal value xx
      • \xhh Character with hex value hh
    7. Methods
      • capitalize() Converts the first character to upper case
      • casefold() Converts string into lower case
      • center() Returns a centered string
      • count() Returns the number of times a specified value occurs in a string
      • encode() Returns an encoded version of the string
      • endswith() Returns true if the string ends with the specified value
      • expandtabs() Sets the tab size of the string
      • find() Searches the string for a specified value and returns the position of where it was found
      • format() Formats specified values in a string
      • format_map() Formats specified values in a string
      • index() Searches the string for a specified value and returns the position of where it was found
      • isalnum() Returns True if all characters in the string are alphanumeric
      • isalpha() Returns True if all characters in the string are in the alphabet
      • isdecimal() Returns True if all characters in the string are decimals
      • isdigit() Returns True if all characters in the string are digits
      • isidentifier() Returns True if the string is an identifier
      • islower() Returns True if all characters in the string are lower case
      • isnumeric() Returns True if all characters in the string are numeric
      • isprintable() Returns True if all characters in the string are printable
      • isspace() Returns True if all characters in the string are whitespaces
      • istitle() Returns True if the string follows the rules of a title
      • isupper() Returns True if all characters in the string are upper case
      • join() Joins the elements of an iterable to the end of the string
      • ljust() Returns a left justified version of the string
      • lower() Converts a string into lower case
      • lstrip() Returns a left trim version of the string
      • maketrans() Returns a translation table to be used in translations
      • partition() Returns a tuple where the string is parted into three parts
      • replace() Returns a string where a specified value is replaced with a specified value
      • rfind() Searches the string for a specified value and returns the last position of where it was found
      • rindex() Searches the string for a specified value and returns the last position of where it was found
      • rjust() Returns a right justified version of the string
      • rpartition() Returns a tuple where the string is parted into three parts
      • rsplit() Splits the string at the specified separator, and returns a list
      • rstrip() Returns a right trim version of the string
      • split() Splits the string at the specified separator, and returns a list
      • splitlines() Splits the string at line breaks and returns a list
      • startswith() Returns true if the string starts with the specified value
      • strip() Returns a trimmed version of the string
      • swapcase() Swaps cases, lower case becomes upper case and vice versa
      • title() Converts the first character of each word to upper case
      • translate() Returns a translated string
      • upper() Converts a string into upper case
      • zfill() Fills the string with a specified number of 0 values at the beginning
  2. list

    1. defining list
      1. list = []
      2. list=[10,20,30,40]
      3. With dynamic input: (eval)
      4. With list() function:
    2. Operations
      1. Indexing
      2. Slicing
      3. Traversing
        1. using for loop
    3. List vs immutability:
    4. cloning Difference between = operator and copy() function
    5. Operators for list
      1. Concatenation operator(+):
      2. Repetition Operator(*):
      3. Comparison ==,!= <,<=,>,>=
      4. in , not in Membership
    6. Nested list Nested List as Matrix:
    7. Comprehensions
    8. Methods
      • append() Adds an element at the end of the list
      • clear() Removes all the elements from the list
      • copy() Returns a copy of the list
      • count() Returns the number of elements with the specified value
      • extend() Add the elements of a list (or any iterable), to the end of the current list
      • index() Returns the index of the first element with the specified value
      • insert() Adds an element at the specified position
      • pop() Removes the element at the specified position
      • remove() Removes the first item with the specified value
      • reverse() Reverses the order of the list
      • sort() Sorts the list
  3. tuple

    1. Defining tuple
      1. t=()
      2. t=(10,)
      3. t=10,20,30
      4. tuple()
    2. Operations
      1. Indexing
      2. Slicing
      3. Traversing using for loop
    3. Tuple vs immutability:
    4. Operators for tuple
      1. Concatenation operator(+):
      2. Repetition Operator(*):
      3. in , not in Membership
    5. Tuple Packing and Unpacking:
    6. Tuple comprehension
    7. Methods
      • count() Returns the number of times a specified value occurs in a tuple
      • index() Searches the tuple for a specified value and returns the position of where it was found
  4. range

Set Sequence Types

  1. set

    1. Defining set
      1. using set()
    2. Set vs immutability:
    3. Operations:
      1. Union
      2. Intersection
      3. Difference
      4. Symmetric difference
    4. Operators for set
      1. Membership operators: (in , not in)
    5. Set comprehension
    6. Methods
      • add() Adds an element to the set
      • clear() Removes all the elements from the set
      • copy() Returns a copy of the set
      • difference() Returns a set containing the difference between two or more sets
      • difference_update() Removes the items in this set that are also included in another, specified set
      • discard() Remove the specified item
      • intersection() Returns a set, that is the intersection of two other sets
      • intersection_update() Removes the items in this set that are not present in other, specified set(s)
      • isdisjoint() Returns whether two sets have a intersection or not
      • issubset() Returns whether another set contains this set or not
      • issuperset() Returns whether this set contains another set or not
      • pop() Removes an element from the set
      • remove() Removes the specified element
      • symmetric_difference() Returns a set with the symmetric differences of two sets
      • symmetric_difference_update() inserts the symmetric differences from this set and another
      • union() Return a set containing the union of sets
      • update() Update the set with the union of this set and others
  2. frozenset

Byte Sequence Types

  1. bytes

  2. bytearray

Map Type: dictionary

  1. dict

    1. Defining dicts
      1. d = {}
      2. d = dict()
    2. Operations
      1. Accessing
      2. Updating dicts
      3. deleting elements
    3. dict comprehensions
    4. Methods
      1. clear() Removes all the elements from the dictionary
      2. copy() Returns a copy of the dictionary
      3. fromkeys() Returns a dictionary with the specified keys and values
      4. get() Returns the value of the specified key
      5. items() Returns a list containing a tuple for each key value pair
      6. keys() Returns a list containing the dictionary's keys
      7. pop() Removes the element with the specified key
      8. popitem() Removes the last inserted key-value pair
      9. setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
      10. update() Updates the dictionary with the specified key-value pairs
      11. values() Returns a list of all the values in the dictionary

• User defined types

  1. class
  2. writing classes

Type Casting

• Implicit type conversion • Explicit type conversion • Type casting functions

  1. int()
  2. float()
  3. complex()
  4. bool()
  5. str()
  6. list()
  7. tuple()
  8. ord()
  9. chr()
  10. bin()
  11. oct()
  12. hex()
  13. set()

Flow controls

  1. Conditionals
    1. if
    2. if-elif
    3. if-elif-else
  2. Iterative
    1. for-else
    2. while-else
  3. Transfer
    1. continue
    2. break

Iterators and Iterable

An object is called iterable if we can get an iterator from it

  1. Creating iterator
  2. Iterating iterator
  3. Internal working of for loop
  4. Building your own iterator
  5. Infinite Iterators
  6. Iterators terminating on the shortest input sequence
  7. Combinatoric Generators

Everything is object

  1. Data types as object
  2. Function as objects
  3. Classes as object
  4. Type as object

Special variables

  1. __bases__
  2. __builtins__
  3. __call__
  4. __class__
  5. __closure__
  6. __dict__
  7. __doc__
  8. __file__
  9. __init__
  10. __init_subclass__
  11. __loader__
  12. __main__
  13. __metaclass__
  14. __module__
  15. __new__
  16. __name__
  17. __package__
  18. __prepare__
  19. __slots__
  20. __subclasshook__
  21. __spec__
  22. __weakref__

Functions:

  1. User Defined Functions

    1. defining a function

    2. calling a function

    3. returning from function

    4. namespace

    5. global Vs local variables

    6. main function

    7. function arguments

      1. positional args
      2. default args
      3. keyword args
      4. **args
      5. **kwargs
    8. function aliasing

    9. Function as a argument

      1. calling passed function
      2. returning passed function call
      3. returning passed function reference
    10. Nested functions

      1. defining nested function
      2. calling nested function
      3. returning nested functions which is not returning value
      4. returning nested functions which is returning value
      5. returning nested function reference which is not returning value
      6. returning nested function reference which is returning value
      7. function closure
      8. use of global keyword
      9. use of nonlocal keyword
    11. generators

      1. Defining generators
      2. Using generator expressions
      3. yield from
      4. send()
    12. Lambda function

    13. Recursive functions

  2. Built in Functions

    1. Math

      1. abs() Returns absolute value of a number
      2. divmod() Returns quotient and remainder of integer division
      3. max() Returns the largest of the given arguments or items in an iterable
      4. min() Returns the smallest of the given arguments or items in an iterable
      5. pow() Raises a number to a power
      6. round() Rounds a floating-point value
      7. sum() Sums the items of an iterable
    2. Type Conversion

      1. ascii() Returns a string containing a printable representation of an object
      2. bin() Converts an integer to a binary string
      3. bool() Converts an argument to a Boolean value
      4. chr() Returns string representation of character given by integer argument
      5. complex() Returns a complex number constructed from arguments
      6. float() Returns a floating-point object constructed from a number or string
      7. hex() Converts an integer to a hexadecimal string
      8. int() Returns an integer object constructed from a number or string
      9. oct() Converts an integer to an octal string
      10. ord() Returns integer representation of a character
      11. repr() Returns a string containing a printable representation of an object
      12. str() Returns a string version of an object
      13. type() Returns the type of an object or creates a new type object
    3. Iterables and Iterators

      1. all() Returns True if all elements of an iterable are true
      2. any() Returns True if any elements of an iterable are true
      3. enumerate() Returns a list of tuples containing indices and values from an iterable
      4. filter() Filters elements from an iterable
      5. iter() Returns an iterator object
      6. len() Returns the length of an object
      7. map() Applies a function to every item of an iterable
      8. next() Retrieves the next item from an iterator
      9. range() Generates a range of integer values
      10. reversed() Returns a reverse iterator
      11. slice() Returns a slice object
      12. sorted() Returns a sorted list from an iterable
      13. zip() Creates an iterator that aggregates elements from iterables
    4. Composite Data Type

      1. bytearray() Creates and returns an object of the bytearray class
      2. bytes() Creates and returns a bytes object (similar to bytearray, but immutable)
      3. dict() Creates a dict object
      4. frozenset() Creates a frozenset object
      5. list() Constructs a list object
      6. object() Returns a new featureless object
      7. set() Creates a set object
      8. tuple() Creates a tuple object
    5. Classes, Attributes, and Inheritance

      1. classmethod() Returns a class method for a function
      2. delattr() Deletes an attribute from an object
      3. getattr() Returns the value of a named attribute of an object
      4. hasattr() Returns True if an object has a given attribute
      5. isinstance() Determines whether an object is an instance of a given class
      6. issubclass() Determines whether a class is a subclass of a given class
      7. property() Returns a property value of a class
      8. setattr() Sets the value of a named attribute of an object
      9. super() Returns a proxy object that delegates method calls to a parent or sibling class
    6. Input/Output

      1. format() Converts a value to a formatted representation

      2. input() Reads input from the console

      3. open() Opens a file and returns a file object

        1. Access modes

          1. It opens a file in read-only mode while the file offset stays at the root.
          2. It opens a file in (binary + read-only) modes. And the offset remains at the root level.
          3. <r+> It opens the file in both (read + write) modes while the file offset is again at the root level.
          4. <rb+> It opens the file in (read + write + binary) modes. The file offset is again at the root level.
          5. It allows write-level access to a file. If the file already exists, then it’ll get overwritten. It’ll create a new file if the same doesn’t exist.
          6. Use it to open a file for writing in binary format. Same behavior as for write-only mode.
          7. <w+> It opens a file in both (read + write) modes. Same behavior as for write-only mode.
          8. <wb+> It opens a file in (read + write + binary) modes. Same behavior as for write-only mode.
          9. It opens the file in append mode. The offset goes to the end of the file. If the file doesn’t exist, then it gets created.
          10. It opens a file in (append + binary) modes. Same behavior as for append mode.
          11. <a+> It opens a file in (append + read) modes. Same behavior as for append mode.
          12. <ab+> It opens a file in (append + read + binary) modes. Same behavior as for append mode.
          13. 'x' Creates a new file. If file already exists, the operation fails.
          14. 't' This is the default mode. It opens in text mode.
          15. 'b' This opens in binary mode.
        2. Methods

          1. close() Close an open file. It has no effect if the file is already closed.
          2. detach() Separate the underlying binary buffer from the TextIOBase and return it.
          3. fileno() Return an integer number (file descriptor) of the file.
          4. flush() Flush the write buffer of the file stream.
          5. isatty() Return True if the file stream is interactive.
          6. read(n) Read atmost n characters form the file. Reads till end of file if it is negative or None.
          7. readable() Returns True if the file stream can be read from.
          8. readline(n=-1) Read and return one line from the file. Reads in at most n bytes if specified.
          9. readlines(n=-1) Read and return a list of lines from the file. Reads in at most n bytes/characters if specified.
          10. seek(offset,from=SEEK_SET) Change the file position to offset bytes, in reference to from (start, current, end).
          11. seekable() Returns True if the file stream supports random access.
          12. tell() Returns the current file location.
          13. truncate(size=None) Resize the file stream to size bytes. If size is not specified, resize to current location.
          14. writable() Returns True if the file stream can be written to.
          15. write(s) Write string s to the file and return the number of characters written.
          16. writelines(lines) Write a list of lines to the file.
      4. print() Prints to a text stream or the console

      5. Variables, References, and Scope

      6. Function Description

      7. dir() Returns a list of names in current local scope or a list of object attributes

      8. globals() Returns a dictionary representing the current global symbol table

      9. id() Returns the identity of an object

      10. locals() Updates and returns a dictionary representing current local symbol table

      11. vars() Returns dict attribute for a module, class, or object

    7. Miscellaneous

      1. callable() Returns True if object appears callable
      2. compile() Compiles source into a code or AST object
      3. eval() Evaluates a Python expression
      4. exec() Implements dynamic execution of Python code
      5. hash() Returns the hash value of an object
      6. help() Invokes the built-in help system
      7. memoryview() Returns a memory view object
      8. staticmethod() Returns a static method for a function
      9. __import__() Invoked by the import statement

Context Managers

  1. Using built in context managers
  2. Multiple context managers with “with”
  3. Creating custom context managers -- OOP

Exception handling

  1. Syntax error

  2. Built-in Exceptions

  3. Raising exceptions

  4. Handling exception with try … except

  5. Built-in exception hierarchy

    1. BaseException
        * SystemExit
        * KeyboardInterrupt
        * GeneratorExit
        * Exception
            * StopIteration
            * StopAsyncIteration
            * ArithmeticError
                * FloatingPointError
                * OverflowError
                * ZeroDivisionError
            * AssertionError
          * AttributeError
          * BufferError
          * EOFError
          * ImportError
              * ModuleNotFoundError
          * LookupError
              * IndexError
              * KeyError
          * MemoryError
          * NameError
            * UnboundLocalError
          * OSError
              * BlockingIOError
              * ChildProcessError
              * ConnectionError
                  * BrokenPipeError
                  * ConnectionAbortedError
                  * ConnectionRefusedError
                  * ConnectionResetError
              * FileExistsError
              * FileNotFoundError
              * InterruptedError
              * IsADirectoryError
              * NotADirectoryError
              * PermissionError
              * ProcessLookupError
              * TimeoutError
          * ReferenceError
          * RuntimeError
              * NotImplementedError
              * RecursionError
          * SyntaxError
            * IndentationError
                * TabError
          * SystemError
          * TypeError
          * ValueError
            * UnicodeError
              * UnicodeDecodeError
              * UnicodeEncodeError
              * UnicodeTranslateError
          * Warning
               * DeprecationWarning
               * PendingDeprecationWarning
               * RuntimeWarning
               * SyntaxWarning
               * UserWarning
               * FutureWarning
               * ImportWarning
               * UnicodeWarning
               * BytesWarning
               * ResourceWarning
    
  6. Multiple except clause

  7. Multiple exception in single except clause

  8. Try … else clause

  9. Try … Finally, clause

  10. Creating custom exceptions

  11. Customizing custom exceptions -- OOP

  12. Creating custom exceptions


Modular Python


  1. Built-in modules
  2. User defined modules
  3. Imports
    1. Absolute imports
    2. Relative imports
    3. Module aliasing while importing
    4. Member aliasing
  4. Reloading a module
  5. Finding members of module using dir()
  6. if __name__ == '__main__'

Packages


  1. Built-in packages
  2. User defined packages
  3. Use of __init__

Some important builtin modules


  1. String

  2. Os

  3. Sys

  4. Random

  5. Multithreading

  6. Multiprocessing

  7. Logging

  8. Json

  9. Configparser

  10. Datetime

  11. Time

  12. Subprocess

  13. Csv

  14. Email

  15. Smtp

  16. http

  17. Itertools

  18. functools

  19. Collections

  20. Request,

  21. Paramiko,

  22. pyyaml

  23. re

    1. Metacharacters:

      1. \ escape special characters
      2. . matches any character
      3. ^ matches beginning of string
      4. $ matches end of string
      5. [5b-d] matches any chars '5', 'b', 'c' or 'd'
      6. [^a-c6] matches any char except 'a', 'b', 'c' or '6'
      7. R|S matches either regex R or regex S
      8. () creates a capture group and indicates precedence
    2. Quantifiers

      1. * 0 or more (append ? for non-greedy)
      2. + 1 or more (append ? for non-greedy)
      3. ? 0 or 1 (append ? for non-greedy)
      4. {m} exactly mm occurrences
      5. {m, n} from m to n. m defaults to 0, n to infinity
      6. {m, n}? from m to n, as few as possible
    3. Special sequences

      1. \A start of string
      2. \b matches empty string at word boundary (between \w and \W)
      3. \B matches empty string not at word boundary
      4. \d digit
      5. \D non-digit
      6. \s whitespace: [ \t\n\r\f\v]
      7. \S non-whitespace
      8. \w alphanumeric: [0-9a-zA-Z_]
      9. \W non-alphanumeric
      10. \Z end of string
      11. \g<id> matches a previously defined group
      12. (?iLmsux) matches empty string, sets re.X flags
      13. (?:...) non-capturing version of regular parentheses
      14. (?P...) matches whatever matched previously named group
      15. (?P=) digit
      16. (?#...) a comment; ignored
      17. (?=...) lookahead assertion: matches without consuming
      18. (?!...) negative lookahead assertion
      19. (?<=...) lookbehind assertion: matches if preceded
      20. (?<!...) negative lookbehind assertion
      21. (?(id)yes|no) match 'yes' if group 'id' matched, else 'no'
    4. Method:

      1. match() Returns match object on successful search
      2. findall() Returns a list containing all matches
      3. search() Returns a Match object if there is a match anywhere in the string
      4. split() Returns a list where the string has been split at each match
      5. sub() Replaces one or many matches with a string
      6. subn() The re.subn() is similar to re.sub() except it returns a tuple of 2 items containing the new string and the number of substitutions made.
    5. Flags:

      1. [re.M] Make begin/end consider each line
      2. [re.I] It ignores case
      3. [re.S] Make [ . ]
      4. [re.U] Make { \w,\W,\b,\B} follows Unicode rules
      5. [re.L] Make {\w,\W,\b,\B} follow locale
      6. [re.X] Allow comment in Regex
  24. sqlite

    1. DB-API
    2. Modules
    3. Connections
    4. Cursors
    5. Connection strings
    6. Exceptions
    7. Methods
      1. connect()
      2. execute()
      3. executemany()
      4. fetch()
      5. fetchone()
      6. fetchall()
      7. close()

Python project setup


  1. Project structure

Package management


  • What is PIP
  • easy_install
  • Managing packages
  • Packaging python apps
  • Distributing python apps
  • Publishing python apps

Deployment


  1. Virtual environments

    1. Using Pipenv
    2. Using virtualenv
  2. activating and deactivating envs

  3. Dependency management in virtual environment

  4. Self-terminating scripts

  5. Infinite running scripts

  6. Scripts with systemctl services

  7. Python variables

    1. PYTHONSTARTUP:

      • file executed on interactive startup (no default)
    2. PYTHONPATH:

      • ':'-separated list of directories prefixed to the default module search path. The result is sys.path.
    3. PYTHONHOME:

      • alternate directory (or :<exec_prefix>). The default module search path uses /lib/pythonX.X.
    4. PYTHONCASEOK:

      • ignore case in 'import' statements (Windows).
    5. PYTHONIOENCODING:

      • Encoding[:errors] used for stdin/stdout/stderr.
    6. PYTHONFAULTHANDLER:

      • dump the Python traceback on fatal errors.
    7. PYTHONHASHSEED:

      • if this variable is set to 'random', a random value is used to seed the hashes of str, bytes and datetime objects. It can also be set to an integer in the range [0,4294967295] to get hash values with a predictable seed.
    8. PYTHONMALLOC:

      • set the Python memory allocators and/or install debug hooks on Python memory allocators. Use PYTHONMALLOC=debug to install debug hooks.
    9. PYTHONCOERCECLOCALE:

      • if this variable is set to 0, it disables the locale coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of locale coercion and locale compatibility warnings on stderr.
    10. PYTHONBREAKPOINT:

      • if this variable is set to 0, it disables the default debugger. It can be set to the callable of your debugger of choice.
    11. PYTHONDEVMODE:

      • enable the development mode.

Development best practices


  1. Code tags
  2. PEP standards
  3. Doc strings
  4. Naming convention

Object Oriented Python


Classes and Objects

  1. class

  2. object

    1. in Python, everything is an object.
    2. new, init
  3. Old style and new style classes

    1. class != type -- old --upto P2.2
    2. class == type -- new --P3
  4. self Reference variable

  5. Constructor

    1. init
  6. Variables

    1. Access modifiers

      1. public, protected, private
    2. Instance variables

      1. Operations
        1. Creation
          1. Inside Constructor by using self variable
          2. Inside Instance Method by using self variable:
          3. Outside of the class by using object reference variable:
        2. Access We can access instance variables with in the class by using self variable and outside of the class by using object reference.
        3. Deletion
          1. Within a class we can delete instance variable as follows del self.variableName
          2. From outside of class we can delete instance variables as follows del objectreference.variableName
    3. static variables

      1. Operations
        1. Creation
          1. In general we can declare within the class directly but from out side of any method
          2. Inside constructor by using class name
          3. Inside instance method by using class name
          4. Inside classmethod by using either class name or cls variable
          5. Inside static method by using class name
        2. Access
          1. inside constructor: by using either self or classname
          2. inside instance method: by using either self or classname
          3. inside class method: by using either cls variable or classname
          4. inside static method: by using classname
          5. From outside of class: by using either object reference or classnmae
        3. Modification If we change the value of static variable by using either self or object reference variable:
        4. Deletion We can delete static variables from anywhere by using the following syntax del classname.variablename But inside classmethod we can also use cls variable del cls.variablename
    4. local variables

      1. Operations
        1. Creation
        2. Access
        3. Modification
        4. Deletion
  7. Methods

    1. Instance methods
    2. Class methods
    3. Static methods
  8. Inner classes:

  9. class decorator

    1. implement init
    2. implement call
  10. nested methods

  11. slots

  12. Meta classes

    1. They allow customization of class instantiation.

    2. Metaclasses are sometimes referred to as class factories.

    3. When defining a class and no metaclass is defined the default type metaclass will be used

    4. the type of any new-style class is type.

    5. The type of the built-in classes you are familiar with is also type:

    6. For that matter, the type of type is type as well (yes, really):

    7. type is a metaclass, of which classes are instances

    8. In the above case:

      1. x is an instance of class Foo.
      2. Foo is an instance of the type metaclass.
      3. type is also an instance of the type metaclass, so it is an instance of itself.
    9. Creation

      1. one
        1. using separate class
        2. implement new with cls, name, base, dct
        3. call super().new(cls, name, bases, dct)
        4. add this newly created metaclass via metaclass= kwarg
      2. two
        1. Inheriting class that has already passed in metaclass= kwarg
    10. singletons using meta

  13. Dynamic creation of classes

    1. The built-in type() function, when passed one argument, returns the type of an object. For new-style classes
    2. You can also call type() with three arguments—type(, , ):
      1. specifies the class name. This becomes the name attribute of the class.
      2. specifies a tuple of the base classes from which the class inherits. This becomes the bases attribute of the class.
      3. specifies a namespace dictionary containing definitions for the class body. This becomes the dict attribute of the class.
    3. Calling type() in this manner creates a new instance of the type metaclass. In other words, it dynamically creates a new class.
  14. Garbage collection

    1. module gc
  15. Destructors

    1. Like Destructor is counter-part of a Constructor, function del is the counter-part of function new. Because new is the function which creates the object.
    2. del method is called for any object when the reference count for that object becomes zero.
    3. As reference counting is performed, hence it is not necessary that for an object del method will be called if it goes out of scope. The destructor method will only be called when the reference count becomes zero.
    4. Exception in init method

Object Relationships (Passing members of one class to another class)

  1. Composition / HAS-A

    1. code reusability
    2. classes is composed of one or more instance of other classes.
    3. weak relation
  2. Inheritance/ Aggregation / IS-A

    1. code reusability

    2. Strong relation

    3. Exceptions Are an Exception

    4. Exception class do not derived from object

    5. Types

      1. Single
        1. single parent, single child, A -> B
      2. Multilevel
        1. A -> B -> C
      3. Hierarchical
        1. single parent, multiple child A -> B, A -> C, A -> D
      4. Multiple
        1. Many parent, single child, A, B -> C
      5. Cyclic
        1. class itself is parent and child, A -> B -> A
      6. Hybrid
        1. single, multilevel, hierarchical, multiple
    6. MRO (Method resolution order)

      1. It tells Python how to search for inherited methods.
      2. depth first, left to right
      3. mro(), __mro__
      4. c3 linearization algorithm
        1. start
        2. mro(X) = X + merge(mro(P1), mro(P2), parent list ie. P1P2)
        3. If head element of first list not present in the tail part of any other list then consider that element in the result
        4. remove that element from all the lists.
        5. else leave the first list as it is and consider the next list and repeat
        6. end
    7. super(): calls parent of your child unlike any other language in which super calls to the parent

      1. call parent class constructor from child
      2. call parent class methods from child
      3. call parent class variables from child (non instance variables only)
      4. you can call parent instance, class and static methods from child class constructor
      5. you can call parent instance, class and static methods from child class instance method
      6. you can call parent instance, class and static methods from child class classmethod method
      7. you can call parent instance, class and static methods from child class static method
      8. super is always talks about immediate parent
      9. you can call particular class implementation from child class
        1. one way is className.method_name(self) (constructor also)
        2. other way is super(ClassName, self).method_name()
      10. Technically, super() doesn’t return a method. It returns a proxy object.
      11. This is an object that delegates calls to the correct class methods without making an additional object.
      12. In Python 3, the super(Square, self) call is equivalent to the parameterless super() call.
      13. A call to the init method of a superclass during object initialization may be omitted:
        1. When a subclass calls the init method of the wrong class.
        2. When a call to the init method of one its base classes is omitted.
        3. When multiple inheritance is used and a class inherits from several base classes, and at least one of those does not use super() in its own init method.
    8. Difference between type and isinstance

      1. type() simply returns the type of an object.
      2. isinstance(): returns true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.

Polymorphism

  1. Duck Typing Philosophy of Python

  2. Distinction between Overwriting, Overloading and Overriding

  3. Overwriting

    1. Nothing to do with OOP
    2. Simply make first definition unavailable
  4. Overriding

    1. Constructor overriding
    2. Method Overriding
  5. Overloading:

    1. Operator Overloading

      1. Supported
      2. Magic methods available
      3. Need to implement these methods
    2. Method Overloading

      1. Not possible
      2. If 2 methods having same name but different type of arguments then those methods are said to be overloaded methods.
      3. If we are trying to declare multiple methods with same name and different number of arguments then Python will always consider only last method.
      4. Handling this req
        1. With default args
        2. With var-args
    3. Constructor Overloading

      1. Not possible
      2. If we define multiple constructors then the last constructor will be considered.
  6. Python magic methods (Object oriented python)

    1. Numeric magic methods

      1. Unary operators and functions

        __pos__(self), __neg__(self), __abs__(self), __invert__(self), __round__(self, n), __floor__(self) __ceil__(self), __trunc__(self)

      2. Normal arithmetic operators

        __add__(self, other), __sub__(self, other), __mul__(self, other), __floordiv__(self, other), __div__(self, other) __truediv__(self, other), __mod__(self, other), __divmod__(self, other), __pow__, __lshift__(self, other) __rshift__(self, other), __and__(self, other), __or__(self, other), __xor__(self, other)

      3. Reflected arithmetic operators

        __radd__(self, other), __rsub__(self, other), __rmul__(self, other), __rfloordiv__(self, other) __rdiv__(self, other), __rtruediv__(self, other), __rmod__(self, other), __rdivmod__(self, other) __rpow__, __rlshift__(self, other), __rrshift__(self, other), __rand__(self, other) __ror__(self, other), __rxor__(self, other)

    2. Augmented assignment

      __iadd__(self, other), __isub__(self, other), __imul__(self, other), __ifloordiv__(self, other) __idiv__(self, other), __itruediv__(self, other), __imod__(self, other), __ipow__, __ilshift__(self, other) __irshift__(self, other), __iand__(self, other), __ior__(self, other), __ixor__(self, other)

    3. Type conversion magic methods

      __int__(self), __long__(self), __float__(self), __complex__(self), __oct__(self), __hex__(self) __index__(self), __trunc__(self), __coerce__(self, other)

    4. Representing your Classes.

      __str__(self), __repr__(self), __unicode__(self), __format__(self, formatstr), __hash__(self) __nonzero__(self), __dir__(self), __sizeof__(self)

    5. Controlling Attribute Access

      __getattr__(self, name), __setattr__(self, name, value), __delattr__(self, name), __getattribute__(self, name)

    6. Making Custom Sequences

      __len__(self), __getitem__(self, key), __setitem__(self, key, value), __delitem__(self, key), __iter__(self) __reversed__(self), __contains__(self, item), __missing__(self, key)

    7. Reflection

      __instancecheck__(self, instance), __subclasscheck__(self, subclass)

    8. Context Managers

      __enter__(self), __exit__(self, exception_type, exception_value, traceback)

    9. Building Descriptor Objects

      __get__(self, instance, owner), __set__(self, instance, value), __delete__(self, instance)

    10. Copying

      __copy__(self), __deepcopy__(self, memodict={})

    11. Pickling your own Objects

      __getinitargs__(self), __getnewargs__(self), __getstate__(self), __setstate__(self, state), __reduce__(self) __reduce_ex__(self), __reduce_ex__, __reduce__

Abstraction

  1. What is abstraction

  2. Abstract classes

    1. Abstract class vs Concrete class
  3. Abstract methods

    1. @abstractmethod
    2. @abstractstaticmethod -> depricated P3.3
    3. @abstrctclassmethod -> depricated P3.3
  4. python implementation

    1. module abc
    2. Abstract Base Classes
      1. class ABC
      2. Abstract base classes exist to be inherited, but never instantiated.
      3. You can use leading underscores in your class name to tell that objects of that class should not be created.
    3. Abstract property
  5. Interfaces

    1. Informal Interface
      1. Using Metaclasses
      2. Virtual base class
        1. virtual base classes don’t appear in the subclass MRO.
    2. Formal Interfaces
      1. Using abc.ABCMeta
      2. Using .subclasshook()
      3. Using abc to Register a Virtual Subclass
      4. Using Subclass Detection With Registration
      5. Using Abstract Method Declaration
  6. Difference between Abstract class / Concrete class

Encapsulation

  1. Information hiding
  2. We are all adults here
  3. protected variables
  4. private variables (name mangling)
  5. Setter and Getter Methods:
  6. Property
    1. getter
    2. setter
    3. deleter

Descriptor

Concurrency & Multiprogramming

  1. Multithreading

    1. What Is a Thread?
    2. Starting a Thread
    3. Working With Many Threads
    4. Using a ThreadPoolExecutor
    5. Race Conditions
    6. Basic Synchronization Using Lock
    7. Deadlock
    8. Producer-Consumer Threading
    9. Threading Objects
  2. Multiprocessing

  3. Co-routines

  4. AsyncIO

    1. async & await
    2. Async generator

Testing


Design patterns

  1. Creational Patterns:
  2. Structural Patterns:
  3. Behavioral Patterns:
  4. Design for Testability Patterns:
  5. Fundamental Patterns:

learn-python's People

Contributors

an-anurag avatar dependabot[bot] avatar agundappa-a10 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.