Duck Typing in Python

  • Duck typing is the “type” of the object is a matter of concern only at runtime and you don’t require mentioning the type of the object before you execute any kind of operation on that object.
  • Parts of the standard library in python suppose to use I/O like objects with read or write methods, yet you will pass anything that executes these, without having to inherit from anything.
  • There is another idea in typing lark which is a characteristics of dynamic languages. This is known as duck typing.
  • Example, in a statically typed language we have a concept of including. A few types of object can be included – typically only to objects of the similar type. Although most languages will let you a chance to add an integer to a floating point number – resulting in a floating point number. Attempt to include different types of objects together and the compiler will tell you that you’re not permitted.
  • In Python we have to permit the object to describe what it to be included. The expression 4 + 4 is syntactic sugar for calling the __add__ method of the integer type. It is similar as calling int.__add__(4, 4). It means that if you define a __add__ method for one of your classes you will make all sorts of things happen when you include instances of them together.
  • Many of Python syntax is sugar for underlying methods especially in data access. Accessing members of sequence type objects as well as mapping type objects is complete by using the __getitem__ method of these objects.
a = [0,1 2, 3]
print a[0]
0
b = {'a': 0, 'b': 1}
print b['a']
0
  • The above code is exactly the same as :
a =  [0,1 2, 3]
print list.__getitem__(a, 0)
0
b = {'a': 0, 'b': 1}
print dict._getitem__(b, 'a')
0

Categorized in:

Python

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Share Article:

Leave a Reply

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
100% Free SEO Tools - Tool Kits PRO