Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Sep 26, 2020

Metaclasses in Python | PYTHON LANGUAGE | Coding Winds

                        Metaclasses

Hey guys, we will here learn about metaclasses in python.

The term metaprogramming refers to the potential for a program to have knowledge of or manipulate itself. Python supports a form of metaprogramming for classes called metaclasses.

Metaclasses are an esoteric OOP concept, lurking behind virtually all Python code. You are using them whether you are aware of it or not. For the most part, you don’t need to be aware of it. Most Python programmers rarely, if ever, have to think about metaclasses.

 

“Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don’t (the people who actually need them know with certainty that they need them, and don’t need an explanation about why).”                 

- Tim Peters

 

There are some python programmers who believe you should never use custom metaclasses. They think that custom metaclasses aren’t necessary.

Still, understanding Python metaclasses is worthwhile, because it leads to a better understanding of the internals of Python classes in general. You never know, you may one day find yourself in one of those situations where you just know that a custom metaclasses is what you want.

Before proceeding further we should know about old-style and new-style classes.

Old-style classes

With old-style classes, class and type are not quite the same thing.

 An instance of an old-style class is always implemented from a single built-in type called instance. If obj is an instance of an old-style class, obj.__class__ designates the class, but type (obj) is always instance.

Let’s look at the example in python 2.7,

 


New-style classes

New-style classes unify the concepts of class and type. If obj is an instance of a new-style class, type(obj) is the same as obj.__class__ (in python3):

Note: - The type of x is class Foo, as you would expect. But the type of Foo, the class itself, is type. In general, the type of any new-style class is type.

The type of the built-in classes you are familiar with is also type, i.e.  int float, dict, list, tuple

We know why type()  is used for, determining the type of object used.

Example, 


You can also call type() with three arguments—type(<name>, <bases>, <dct>):

  • <name> specifies the class name. This becomes the __name__ attribute of the class.
  • <bases> specifies a tuple of the base classes from which the class inherits. This becomes the __bases__ attribute of the class.
  • <dct> specifies a namespace dictionary containing definitions for the class body. This becomes the __dict__ attribute of the class.

Calling type() in this manner creates a new instance of the type metaclass. In other words, it dynamically creates a new class.



Custom Metaclasses

Look at the example below,

The expression Foo() creates a new instance of class Foo. When the interpreter encounters Foo(), the following occurs:

  • The __call__() method of Foo’s parent class is called. Since Foo is a standard new-style class, its parent class is the type metaclass, so type’s __call__() method is invoked.
  • That __call__() method in turn invokes the following:
    • __new__()
    • __init__()

If Foo does not define __new__() and __init__(), default methods are inherited from Foo’s ancestry. But if Foo does define these methods, they override those from the ancestry, which allows for customized behaviour when instantiating Foo.

In the following, a custom method called new() is defined and assigned as the __new__() method for Foo:


This modifies the instantiation behaviour of class Foo: each time an instance of Foo is created, by default it is initialized with an attribute called attr, which has a value of 100. (Code like this would more usually appear in the __init__() method and not typically in __new__(). This example is contrived for demonstration purposes.)


Sep 8, 2020

Map, Filter, Reduce | Python | PYTHON Language | Coding Winds

                                             Map, Filter, Reduce

So guys, this is where we start the advance programming in python.

Map, Filter, and Reduce are paradigms of functional programming. They allow the programmer (you) to write simpler, shorter code, without necessarily needing to bother about intricacies like loops and branching.

MAP

Map comes built-in with python and requires no importing.

The syntax is,

map(function, *iterables)

Where function is the function on which each element in iterables (as many as they are) would be applied on. Notice the asterisk (*) on iterables? It means there can be as many iterables as possible, in so far function has that exact number as required input arguments.

Before proceeding further, please keep these in mind:-

·       In python 2, the map() function returns a list. In python 3, the function returns a map object which is a generator object. In order to obtain list in Python 3 through map (), a built-in list()  function can be called on the map object, list(map(function, *iterables))

·       The number of arguments to function must be the number of iterables listed.

Look carefully on these codes,

Simple and length code













Advance plus easier a lot flexible







You will see that these both different code will lead to the same output,






Note-That we did not call the str.upper function (doing this: str.upper()), as the map function does that for us on each element in the pilots_speed list.

What's more important to note is that the str.upper function requires only one argument by definition and so we passed just one iterable to it. So, if the function you're passing requires two, or three, or n arguments, then you need to pass in two, three or n iterables to it

Lets look at another example,






See the beauty of map()? Can you imagine the flexibility this evokes?

The range(1,7) function acts as the second argument to the round function.

The result will be,

We will now use the zip() function that takes a number of iterables and then creates a tuple containing each of the elements in the iterables.











We can generate the same output with map() function












Look out the output and understand.

 

FILTER

Filter comes built-in with python and requires no importing.

Unlike map(), filter(), first of all, requires the function to return Boolean value(true or false) and then passes each element in the iterable through the function, "filtering" away those that are false.

Its syntax is,

                                      filter(function, iterable)

Before proceeding further to examples there are some points to be kept in mind:

·       Unlike map(), only one iterable is required.

·       The function argument is required to return a boolean type. If it doesn't, filter simply returns the iterable passed to it. Also, as only one iterable is required, it's implicit that function must only take one argument.

·       filter passes each element in the iterable through function and returns only the ones that evaluate to true.

Lets look at the below example,









Yess, the output will be marks more than 75(excluding 75). Pretty simple and neat, right?

REDUCE

Reduce applies a function of two arguments cumulatively to the elements of an iterable, optionally starting with an initial argument.

Reduce needs to be imported as it resides in the functools module.

Its syntax is,

reduce(function, iterable, initial_value)


Before proceeding further, take a look at these points:-

·       function requires two arguments,t he first of which is the first element in iterable (if initial is not supplied) and the second the second element in iterable. If initial is supplied, then it becomes the first argument to function and the first element in iterable becomes the second element.

·       reduce "reduces" (I know, forgive me) iterable into a single value

Now lets look at some examples,












What if you add these numbers through the built-in function in python , sum().

We will get the same output, 105. We customized our code similarly the sum() function works.

What if we change the initial value to 10?

Will the output will still be the same? Check out yourself. 

Aug 21, 2020

Modules in Python | PYTHON Language | Coding Winds

Modules

A module is a file containing Python definitions and statements. To create modules, you just need to set your coding game and save the files as .py

Look at the code below,


Save it as fibo.py

We have successfully created a module and will use it in our code.

Using modules

Now we can use the module we just created, by using the import statement:

Output here will yield all Fibonacci numbers till 200.

Renaming modules

We can simply rename any module as per our way of usage.

Create an alias for mymodule called mx:

Built-in Modules

Built-in modules are written in C and integrated with the Python interpreter. Each built-in module contains resources for certain system-specific functionalities such as OS management, disk IO, etc. The standard library also contains many Python scripts (with the . py extension) containing useful utilities.

There are several built-in modules in Python, which you can import whenever you like.

Output

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module. The dir () function:

Note: The dir() function can be used on all modules, also the ones you create yourself.