Showing posts with label coding in python. Show all posts
Showing posts with label coding in 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. 

Jul 20, 2020

Functions in Python | PYTHON Language | Coding Winds

Python Functions

Hello guys, we will in this blog learn about Python functions.  A function is statements written in that works only when called.

A function in Python is defined with the def keyword. Functions do not have declared return types. A function without an explicit return statement returns None. In the case of no arguments and no return value, the definition is very simple.

Calling the function is performed by using the call operator () after the name of the function.


1.png

Arguments

The arguments of a function are defined within the def statement. Like all other variables in Python, there is no explicit type associated with the function arguments.

Function arguments can optionally be defined with a default value. The default value will be assigned in the case that the argument is not present in the call to the function. All arguments without default values must be listed before arguments with default values in the function definition.

2.png

Default value of score if not mention while calling the function will be zero.

What if we change the position of arguments, will it work the same?

3.png

Check the output. Doubt cleared?

Note: - Look carefully at the example above. There is an asymmetry in the use of the = sign for defining vs. passing arguments that can be confusing to beginners. An argument with a default value can be passed using only position and an argument without a default can be passed using a keyword.

Mutable Arguments and Binding of Default Values

When defining default arguments, take special care with mutable data types. The instance of the default value is bound at the time the function is defined. Consequently, there is a single instance of the mutable object that will be used across all calls to the function.

4.png

As a result of the above its is useful to use default value as None. 

5.png

Error in the code. Instead of baseitem=[], it should be baseitem=None.

Accepting Variable Arguments

Functions can have two special arguments. 

The first is a variable-length, named tuple of any additional positional arguments received by the function. This special argument is identified by prefixing it with *. 

The second is a variable-length dictionary containing all keyword arguments passed to the function that were not explicitly defined as part of the function arguments. This is identified by **.

It is not required, but for easiness, to name these two arguments args and kwargs.

6.png

Use the function, and note the output.

Watch out sometimes complex functioning gives rise to errors.

Unpacking Argument Lists

It is also possible to construct argument lists (positional or keyword) and pass them into a function.

For positional arguments, insert them into a tuple / list and prepend with an asterisk (*) in the function call.

For keyword arguments, use a dictionary and prepend with two asterisks (**).

7.png

Note: The example above shows another potentially confusing asymmetry in Python. You can pass arguments using the regular style to a function defined using variable arguments, and you can pass unpacked variable argument lists to a function defined without variable arguments.

Scope

Each function evaluation creates a local namespace that is manipulated at any level within the function.

So, variables can be initially defined at a seemingly lower level of scope than they are eventually used.

8.png


Note: This model for scope can simplify your code, but pay attention. If you don’t anticipate all code paths, you can end up referencing undefined variables.

Jul 3, 2020

Dictionary Comprehensions | Dictionary in Python | Coding Winds

Dictionary Comprehension

Hello guys, here we will talk about dictionary comprehension.

Dictionary comprehension is a precise way to create a new dictionary from the existing dictionary in python

Syntax is,

{key: expression for x in iterable if conditional}

Output

Another example,

Output

Single If statement

Output

We see that the conditional statement worked properly.

Similarly we can use multiple If loop and if-else also.

Nested dictionary with two dictionary comprehensions

Output

This code without dictionary comprehension will look like this,

We must be careful while using dictionary comprehension as:

1)     They can sometimes make the code run slower and consume more memory.

2)     They can also decrease the readability of the code.


  Hello Python people, for this blog we have taken help from the book Python : The Complete Reference.

Hope all your doubts regarding this are clear now.

If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".


Do subscribe to our daily blog update by clicking here.


Thank You!


Jun 29, 2020

Dictionary in Python | Initializing | Deletion | Addition | Coding Winds |

Python Dictionary

Hello guys, we will be discussing about Python Dictionary. It is an unordered representation and collection of items. Each item has a key/value pair. They are to obtain value when the key is known.

Initializing of dictionary

Initializing a dictionary requires the elements to be in between the {} brackets. Each item has a key and a corresponding value expressed as a pair. Representation is shown below,

Output

As seen we have used built-in function, dict(), to create a dictionary.

Accessing elements from dictionary

We use indexing to access other data types but in dictionary, we use keys. Keys can be used either inside square brackets [] or with the get() method.

KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.

Output

Changing and Adding of Elements

Dictionaries are mutable. We can easily add or change items using an assignment operator.

Output

Removal of Elements from Dictionary

We use pop() to remove a particular item from a dictionary. This removes an item with the provided key and returns the value. popitem()  can also be used, but this method selects the element randomly and return the item pair from the dictionary. clear() will empty the dictionary while del  will delete the dictionary or can be used to delete a specific item.

Output

Python Dictionary Methods

We have discussed few of the methods above like pop(), del, popitem(), get(), clear()

1)     Python Dictionary fromkeys()

It creates a new dictionary with the sequence of elements with a value provided by the user.

Syntax is,

dictionary.fromkeys(sequence, keys)

Sequence: - a sequence of elements which is to be used as keys for the new dictionary.

Value (optional): - values which will be set to each element of the dictionary by the user.

A dictionary from mutable object list,

Output

2)     Python Dictionary values()

It returns the list of all the values in the dictionary.

The syntax is,

dictionary.value()

This doesn’t take any parameters.

Output

What if the dictionary is modified?

Output

3)     Python Dictionary update()

The syntax is,

dict.update(other)

 This actually adds elements (from another dictionary, d1) if the key is not in dictionary, d. If the key is there then it updates the value of the key.

How update() works with an iterable?

Output

4)     Python Dictionary keys()

It returns the list of all the keys in the dictionary.

The syntax is,

dict.keys()

This doesn’t take any parameters

Look for the output on your own for better understanding.

5)     Python Dictionary items()

It returns the list of dictionary’s tuple pairs.

The syntax is,

dict.items()

This doesn’t take any parameters

Look for the output on your own for better understanding.

6)     Python Dictionary setdefault()

The setdefault() method returns the value of a key. If not, it inserts key with a value to the dictionary.

The syntax is,

dict.setdefault(key, defaultvalue)

Key: - key to be searched in the dictionary

Defaultvalue: - key with a value defaultvalue is inserted to the dictionary if key is not in the dictionary. If not provided, the defaultvalue will be None.

When key is the dictionary,

The output will be the value of the key which is 0.

When the key is not in the dictionary,

Check out the output.

 

PYTHON DICTIONARY COMPREHENSION

 

 Hello Python people, for this blog we have taken help from the book Python : The Complete Reference.

Hope all your doubts regarding this are clear now.

If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".


Do subscribe to our daily blog update by clicking here.


Thank You!