Showing posts with label coding winds. Show all posts
Showing posts with label coding winds. 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 21, 2020

Destructors in C++ | C++ Language | Coding Winds

                                                            Destructors

 

You all must have heard about constructors, it's uses and properties. If you haven't then I recommend you to first read the article about constructors (link given below)

 

https://codingwinds.blogspot.com/2020/08/constructors-and-destructors-in-c-c.html

 

So, A destructor, as the name suggests , is used to destroy the objects (free the memory space) that have been created by constructor.Just like a constructor, destructor is a member function whose name is same as class name but preceded by a tilde(~) i.e we have to use a tilde before writing a class name to call a destructor.

Now for the betting understand of the concept l, let's talk about It's properties to have a better insight.

 

Properties

-It is called automatically whenever object is destroyed or removed from the memory.

-It is used to perform any operation at the time of destruction of any object.

-It is called as per LIFO(Stack) method.(IMP)

-It cannot have parameters. Thus, it cannot be overloaded.

-It can be virtual.

 

Now let's take an example how the objects are released from the memory.

 

Suppose we have a class whose name is Complex.

Complex c1,c2,c3;

Here c1, c2, c3 are objects of Complex class. So, c3 will be destructed first from the memory, then after c2 will be destructed and finally c1 will be destructed.

 

I hope after reading this article, the topic of destructor will be clear but If you still face some kind of doubt or have any query then you can contact us.

 

Thank you.

Sep 11, 2020

Templates of C++ | C++ Language | Coding Winds

Templates in C++

Hello people, today we are going to read about the templates in C++. This is one of the recently added features of C++. It is a concept which enables us to define generic classes and functions and thus provide support for generic programming. Generic programming is an approach where generic types are used as parameters in algorithms so that they work for a variety of suitable data types and data structures.

A template can be used to create a family of classes or functions. For example, a class template for an array class would enable us to create arrays of various data types such as int array and float array.

Since a template is defined with a parameter that would be replaced by a specified data type at the time of actual use of the class or function, the templates are sometimes called parameterized classes or functions.

The concept of templates can be used in two different ways :

·       Function Templates

·       Class Templates

Function Templates

A function template operates similarly as the normally defined functions does. But with a one major key difference, that in function templates you can use parameters of different types but in normal functions we can use only the already defined type of data types.

We can also use function overloading for using a particular function with parameters different types of data types, but using functions templates is a way much better approach.

Function Templates Declaration

A function template declaration starts with a keyword template followed by templates parameters inside <……> which is followed by function declaration.


In above example, T is the argument of template which accepts different data types (int, floor) and typename is keyword.

We can also use class keyword in place of typename.

When an argument is passed to “function()” compiler generates a completely different version of the “function()” for the given data type.

Class Templates

As function templates we can also create templates for generic classes.

Sometimes, we need a class implementation that is same of all classes, only the data types used are different.

Normally, you would need to create a different class for each type or create different member variables and functions with a single class.

However, class templates make it easy to reuse the same code for all data types.

Class Templates Declaration



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.