esther-86 / Work-Notes

0 stars 0 forks source link

Python documentation #2

Open esther-86 opened 3 years ago

esther-86 commented 3 years ago

https://docs.python.org/3/tutorial/ Intermediate Python course: https://youtu.be/HGOBQPFzWKo

esther-86 commented 3 years ago

When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.z

default to be shared between subsequent calls:

def f(a, L=[]):

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

Using set() on a sequence eliminates duplicate elements. The use of sorted() in combination with set() over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order.

esther-86 commented 3 years ago

You can also write relative imports

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

If the finally clause executes a break, continue or return statement, exceptions are not re-raised.

When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace.

the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x)

Python implementation detail: When a non-data attribute of an instance is referenced (as in a method), the instance’s class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.

There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).

Multiple inheritance: all classes inherit from object, so any case of multiple inheritance provides more than one path to reach object. To keep the base classes from being accessed more than once, the dynamic algorithm linearizes the search order in a way that preserves the left-to-right ordering specified in each class, that calls each parent only once, and that is monotonic (meaning that a class can be subclassed without affecting the precedence order of its parents).

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python

Python name mangling: https://www.geeksforgeeks.org/name-mangling-in-python/

even if MappingSubclass were to introduce a update identifier since it is replaced with _Mapping__update in the Mapping class and _MappingSubclassupdate in the MappingSubclass class respectively.

metaclass=ABCMeta to mean abstract class and cannot create any instances of it: https://youtu.be/-a1PFtooGo4?t=158

Use exception chaining appropriately. raise X from Y should be used to indicate explicit replacement without losing the original traceback. (raise X from None)

Context managers should be invoked through separate functions or methods whenever they do something other than acquire and release resources:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false

Type hints: https://www.python.org/dev/peps/pep-0484/ function annotations

esther-86 commented 3 years ago

Design patterns: https://refactoring.guru/design-patterns/python

esther-86 commented 3 years ago

Factory Method: https://refactoring.guru/design-patterns/factory-method provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created returns the object in a superclass

Use when:

https://www.youtube.com/watch?v=-a1PFtooGo4 and https://youtu.be/s_4ZrtQs8Do describes a part of this, up to item #3 in the "How to Implement". Refactoring,guru went further by creating creator subclasses... This is further explained here... which I don't quite get At first glance, this change may look pointless: we just moved the constructor call from one part of the program to another. However, consider this: now you can override the factory method in a subclass and change the class of products being created by the method.

esther-86 commented 3 years ago

Abstract Factory lets you produce families of related objects without specifying their concrete classes. Similar to Factory Method but returns the factories that will create related objects (https://youtu.be/TAnG6DN-5QM?t=38)

Use when:

esther-86 commented 3 years ago

Builder construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code

Use when:

esther-86 commented 3 years ago

Prototype/Clone lets you copy existing objects without making your code dependent on their classes

Want to: you want to create an exact copy of object. But there’s a catch. Not all objects can be copied that way because some of the object’s fields may be private... Sometimes you only know the interface that the object follows, but not its concrete class...

Solution: delegates the cloning process to the actual objects that are being cloned

Python has import copy module which can do shallow and deep copy. Use this instead? https://youtu.be/HGOBQPFzWKo?t=20072

esther-86 commented 3 years ago

Singleton ensure that a class has only one instance, while providing a global access point to this instance

esther-86 commented 3 years ago

Adapter allows objects with incompatible interfaces to collaborate

An adapter wraps one of the objects to hide the complexity of conversion happening behind the scenes. Since you can't use the incompatible interface directly, you can use the wrapper object.

https://youtu.be/SUsbtMcTh-A?t=326

esther-86 commented 3 years ago

Bridge lets you split a large class or a set of closely related classes into two separate hierarchies—abstraction and implementation—which can be developed independently of each other.

Happens when we’re trying to extend the [] classes in x independent dimensions

Instead of having combinational shape and color classes Have Shape class and Color class and have Shape class contain reference to Color class. This is the bridge.

https://youtu.be/t0mCrXHsLbI?t=744

esther-86 commented 3 years ago

Composite lets you compose objects into tree structures and then work with these structures as if they were individual objects

Use when:

DistinctElementA - folder, DistinctElementB - file Composite - list of folder & file grouped together

https://youtu.be/_uOwULztBgM?t=211

esther-86 commented 3 years ago

Decorator/Wrapper attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors

Has reference to "undecorated" object and same method call, but do something "extra" in the function https://youtu.be/mIJDfeMTXGE?t=196

Use when:

Relations with other patterns:

esther-86 commented 3 years ago

Facade simplified interface to a library, a framework, or any other complex set of classes A facade might provide limited functionality in comparison to working with the subsystem directly. However, it includes only those features that clients really care about. handy when you need to integrate your app with a sophisticated library that has dozens of features, but you just need a tiny bit of its functionality. defines a new interface for existing objects

Use when:

esther-86 commented 3 years ago

Flyweight lets you fit more objects into the available amount of **RAM** by sharing common parts of state between multiple objects instead of keeping all of the data in each object. should initialize its state just once, via constructor parameters. Should be immutable.

an object that only stores the intrinsic state is called a flyweight extrinsic state moved to the container object, which aggregates objects before we apply the pattern.

constant data of an object is usually called the intrinsic state. It lives within the object; other objects can only read it, not change it. The rest of the object’s state, often altered “from the outside” by other objects, is called the extrinsic state.

For more convenient access to various flyweights, you can create a factory method that manages a pool of existing flyweight objects.

esther-86 commented 3 years ago

Proxy provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.

new proxy class with the same interface as an original service object. Upon receiving a request from a client, the proxy creates a real service object and delegates all the work to it. If you need to execute something either before or after the primary logic of the class, the proxy lets you do this without changing that class.

Use when:

esther-86 commented 3 years ago

Chain of Responsibility: https://refactoring.guru/design-patterns/chain-of-responsibility pass requests along a chain of handlers.

Use when:

esther-86 commented 3 years ago

Command: https://refactoring.guru/design-patterns/command turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations.

esther-86 commented 3 years ago

Iterator: https://refactoring.guru/design-patterns/iterator traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.)

one day you might be just fine with depth-first traversal of a tree. Yet the next day you might require breadth-first traversal. And the next week, you might need something else, like random access to the tree elements

esther-86 commented 3 years ago

Mediator: https://refactoring.guru/design-patterns/mediator reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object

Aircraft pilots don’t talk to each other directly when deciding who gets to land their plane next. All communication goes through the control tower.

esther-86 commented 3 years ago

Memento: https://refactoring.guru/design-patterns/memento save and restore the previous state of an object without revealing the details of its implementation

esther-86 commented 3 years ago

Observer/Event-Subscriber/Listener: https://refactoring.guru/design-patterns/observer define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing

esther-86 commented 3 years ago

State: https://refactoring.guru/design-patterns/state object alter its behavior when its internal state changes. It appears as if the object changed its class

Document class. A document can be in one of three states: Draft, Moderation and Published. The publish method of the document works a little bit differently in each state

The biggest weakness of a state machine based on conditionals reveals itself once we start adding more and more states and state-dependent behaviors to the Document class...monstrous conditionals... very difficult to maintain because any change to the transition logic may require changing state conditionals in every method

esther-86 commented 3 years ago

Strategy: https://refactoring.guru/design-patterns/strategy define a family of algorithms, put each of them into a separate class, and make their objects interchangeable

take a class that does something specific in a lot of different ways and extract all of these algorithms into separate classes called strategies

The original class, called context, must have a field for storing a reference to one of the strategies. The context delegates the work to a linked strategy object instead of executing it on its own.

The context isn’t responsible for selecting an appropriate algorithm for the job. Instead, the client passes the desired strategy to the context.

esther-86 commented 3 years ago

Template: https://refactoring.guru/design-patterns/template-method defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure

esther-86 commented 3 years ago

Visitor: https://refactoring.guru/design-patterns/visitor separate algorithms from the objects on which they operate (Export)

place the new behavior into a separate class called visitor, instead of trying to integrate it into existing classes.

system architect refused to allow you to alter existing node classes behavior would look alien would ask you to provide the ability to export into a different format, or request some other weird stuff. This would force you to change those precious and fragile classes again.

Use when:

esther-86 commented 3 years ago

python -V showing 2.7.16 instead of 3.9.*: https://stackoverflow.com/a/56247725/5885721