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

Monday, June 19, 2023

Passing Object of The Class as Parameter in Python

In this post we’ll see how to pass object of the class as parameter in Python.

Passing object as parameter

In the example there are two classes Person and MyClass, object of class Person is passed as parameter to the method of class MyClass.

class MyClass():
  def my_method(self, obj):
    print('In my_method method of MyClass')
    print("Name:", obj.name)
    print("Age:", obj.age)
In MyClass there is one method my_method() which takes self as one of the argument and another argument is obj, that is where I intend to pass an object of Person class.
 
from MyClass import MyClass
class Person:
  def __init__(self, name, age):
    print('init called')
    self.name = name
    self.age = age

  def display(self):
    print('in display')
    print("Name-", self.name)
    print("Age-", self.age)
    # object of class MyClass
    obj = MyClass()
    # passing person object to
    # method of MyClass (self = person here)
    obj.my_method(self)

person = Person('John', 40)
person.display()
In class Person, MyClass is also used so that is imported.
from MyClass import MyClass
In method display() object of MyClass is created.
obj = MyClass()
Then the my_method() method of class MyClass is called and object of Person class is passed as parameter.
 # passing person object to
 # method of MyClass (self = person here)
 obj.my_method(self)
On executing this Python program you get output as following.
init called
in display
Name- John
Age- 40
In my_method method of MyClass
Name: John
Age: 40

That's all for this topic Passing Object of The Class as Parameter in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Class And Object in Python
  2. Constructor in Python - __init__() function
  3. Multiple Inheritance in Python
  4. Method Overloading in Python
  5. Abstract Class in Python

You may also like-

  1. Accessing Characters in Python String
  2. Python Conditional Statement - if, elif, else Statements
  3. Python Program to Display Armstrong Numbers
  4. JVM Run-Time Data Areas - Java Memory Allocation
  5. Linear Search (Sequential Search) Java Program
  6. Passing Arguments to getBean() Method in Spring
  7. Connection Pooling With Apache DBCP Spring Example
  8. Word Count MapReduce Program in Hadoop

Wednesday, June 15, 2022

Local, Nonlocal And Global Variables in Python

In this post we’ll learn about global variables, local variables and nonlocal variables in Python, what is the scope of these variables and usage examples.


Global variable in Python

Variables that are declared outside a function are known as global variables in Python. These variables have a greater scope and are available to all the functions that are defined after the declaration of global variable.

Python global variable example

#global variable
x = 10
def function1():
  y = 7
  print("x in function1=", x)
  print("y in function1=", y)

def function2():
  print("x in function2=", x)

function1()
function2()
#scope here too
print('x=', x)

Output

x in function1= 10
y in function1= 7
x in function2= 10
x= 10

In the example variable x is declared outside any function so it’s scope is global. This global variable x can be accessed inside the functions as well as outside the functions (as done in last print statement).

Local variable in Python

When a variable is declared inside a function then it is a local variable. A local variable’s scope is limited with in the function where it is created which means it is available with in the function where it is declared not outside that function.

If we modify the above example a bit and bring variable x with in the function1() then you will get an error as x won’t be visible in function2() or outside any function.

def function1():
  x = 10
  y = 7
  print("x in function1=", x)
  print("y in function1=", y)

def function2():
  print("x in function2=", x)

function1()
function2()
# no scope here
print('x=', x)

output

x in function1= 10
y in function1= 7
 File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 12, in <module>
    function2()
  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 9, in function2
    print("x in function2=", x)
NameError: name 'x' is not defined

global keyword in Python

As we have learned till now a variable declared outside any function has a global scope where as a variable declared inside any function has a local scope. If you declare a variable inside a function having the same name as the global variable then with in the scope of the method local variable overshadows the global variable.

x = 10
def function():
  #local var
  x = 12
  print("x in function=", x)

function()
# Outside function
print('x=', x)

Output

x in function= 12
x= 10

As you can see here inside function() x has the value 12 even if there is a global variable x with value 10.

Now consider the scenario where you want to modify the global variable itself inside a function. You will get an error ‘local variable 'x' referenced before assignment’ because Python looks for x declaration with in the function which is not found thus the error.

x = 10
def function():
  x = x + 1
  print("x in function=", x)

function()
# Outside function
print('x=', x)

Output

  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 6, in <module>
    function()
  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 3, in function
    x = x + 1
UnboundLocalError: local variable 'x' referenced before assignment

Python global keyword example

In such scenario, where you want to use the global variable inside a function, you can use global keyword with the variable in the start of the function body.

x = 10
def function():
  # to access global variable
  global x
  x = x + 1
  print("x in function=", x)

function()
# Outside function
print('x=', x)

Output

x in function= 11
x= 11

Python global variable in class example

Suppose you want to have a global variable which has to retain its updated value for all the class instances so that any new object gets the updated value. Since, the global statement is a declaration which holds for the entire current code block so using global keyword you can do that as follows.

class MyClass():
  global count
  count = 10

  def mymethod(self):
    global count
    count += 1
    print("count in mymethod=", count)

obj1 = MyClass()
obj1.mymethod()
print('count=', count)
obj2 = MyClass()
obj2.mymethod()
print('count=', count)

Output

count in mymethod= 11
count= 11
count in mymethod= 12
count= 12

As you can see global variable count is updated in the method and the updated value is retained so that the new object gets that value. At the class level x is declared as global that let each new instance know that x has the scope in the whole code block. In the method mymethod count is again declared as global so that the same count variable is used.

Sharing global variables in multiple Python modules

Global variables in Python can be shared across multiple modules. In the example there is a module Test.py that declares two variables.

x = 0
y = ""

In another module (Display.py) Test.py is imported and values are assigned to the variables that are declared in Test.py.

import Test
def display():
  #assigning values to global variables
  Test.x = 7
  Test.y = "Module"
  print('x=',Test.x, 'y=', Test.y)

Then you can import these modules and display values of the variables directly or by calling the function display of Display.py module.

import Display
import Test
Display.display()
print(Test.x)
print(Test.y)

Output

x= 7 y= Module
7
Module

Non-local variables in Python

Non-local variables are created using nonlocal keyword in Python. The nonlocal keyword causes the variable to refer to previously bound variables in the nearest enclosing scope excluding globals.

nonlocal keyword is added in Python 3.

Python nonlocal keyword example

nonlocal keyword is used with variables in nested functions where the variable is in outer scope, by making variable nonlocal it can be accessed in nested function. Let’s clarify it with an example.

In the example there is a function myfunction() where a variable count is declared. In the nested function increment() value of count is incremented. This results in an error ‘UnboundLocalError: local variable 'count' referenced before assignment’ because count variable is in the scope of outer method.

def myfunction():
  count = 0
  #nested function
  def increment():
    count += 1
    return count
  # calling nested function
  print('count is-', increment())
  print('count is-', increment())
  print('count is-', increment())

myfunction()

Output

  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 12, in <module>
    myfunction()
  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 8, in myfunction
    print('count is-', increment())
  File "F:/NETJS/NetJS_2017/Python/Test/HelloWorld.py", line 5, in increment
    count += 1
UnboundLocalError: local variable 'count' referenced before assignment

To ensure that nested function has access to the variable in the enclosing scope, you can use nonlocal keyword with variable in the body of nested function.

def myfunction():
  count = 0

  def increment():
    nonlocal count
    count += 1
    return count
  # calling nested function
  print('count is-', increment())
  print('count is-', increment())
  print('count is-', increment())

myfunction()

Output

count is- 1
count is- 2
count is- 3

That's all for this topic Local, Non-local And Global Variables in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Namespace And Variable Scope in Python
  2. Multiple Inheritance in Python
  3. Method Overloading in Python
  4. self in Python
  5. Getting Substring in Python String

You may also like-

  1. Passing Object of The Class as Parameter in Python
  2. Class And Object in Python
  3. List Comprehension in Python With Examples
  4. How to Sort HashSet in Java
  5. Thread Priorities in Java Multi-Threading
  6. String in Java Tutorial
  7. Autowiring in Spring Using @Autowired and @Inject Annotations
  8. Sequence File in Hadoop

Sunday, June 12, 2022

Namespace And Variable Scope in Python

In this post we’ll see what is Namespace in Python and how different scopes are created as per the operating namespace.


What is name

To understand namespace in Python we’ll start first with what is name?

Here note that in Python numbers, strings, functions, lists etc. are all objects and name is a reference to the memory allocated to that object.

For example when you write num = 5 in Python, num is a name given to refer to the object having value 5.

namespace in python

Namespace in Python

Python namespace helps in ensuring that the names in any program are unique and those names can be used without any conflict.

Namespace in Python is implemented as a dictionary and it is a mapping from names to objects where name acts as a key and the object as a value. That way multiple namespaces may have variables with same names but those are mapped to different objects.

For example if there are two namespaces ns1 and ns2 where ns1 has attributes a and b where as ns2 has attributes a, b and c then the namespace dictionaries for these two namespaces can be depicted as-

ns1={a=obj1, b=obj2}
ns2={a=obj3, b=obj4, c=obj5}

Following Python example tries to clarify the concept of namespace.

class MyClass():
  # class variable in class namespace
  x = 10
  def my_method(self):
    # local namespace
    x = 12
    print("x(local)=", x)

obj1 = MyClass()
obj1.my_method()
# prints the class variable
print("x=", obj1.x)
obj2 = MyClass()
obj2.my_method()
print("x=", obj2.x)

Output

x(local)= 12
x= 10
x(local)= 12
x= 10

As you can see in the example there is a variable with the same name ‘x’ at the class level as well as with in a method. Since both are in different namespace so there is no conflict and both can be accessed as per their scope.

Types of namespaces in Python

In Python namespaces are created at different moments and have different lifetimes.

  1. Built-in namespace- This namespace contains the built-in functions and built-in exception names. Built-in namespace is created when the Python interpreter starts up, and is never deleted.
  2. Global namespace- This namespace contains the names in the modules that you import in your project. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits.
  3. Local namespace- This namespace contains names inside functions. The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function.

Scope in Python

A scope is a code region of a Python program where a namespace is directly accessible. Here directly accessible means that you don’t need to qualify reference to the name using object (i.e. obj.x) or class (i.e. MyClass.x) to find the name in the namespace. As per the available namespaces there are different scopes that can exist too.

  1. Local scope (or the innermost scope) contains the local names. This scope is searched first for any name.
  2. The scopes of any enclosing functions, which are searched starting with the nearest enclosing scope and moving outwards.
  3. Module level scope (next-to-last scope) contains the current module’s global names.
  4. The outermost scope is the namespace containing built-in name. This scope is searched last to find the name in the namespace.

As you can see scopes corresponds to the respective namespaces and names in the scopes are searched starting from innermost moving outwards.

Namespace and variable scope python

Python variable scope example

class MyClass():
  # class variable in class namespace
  x = 10
  def my_method(self):
    # local namespace
    x = 12
    def inner_method():
      x = 16
      print('x value inner', x)

    inner_method()
    print("x(local)=", x)

obj1 = MyClass()
obj1.my_method()
# prints the class variable
print("x=", obj1.x)

Output

x value inner 16
x(local)= 12
x= 10

In the example there is a global variable x with value as 10. There is a variable with the same name in function my_method with value as 12. There is a function inner_method with in the scope of my_method again having a variable x with the value as 16.

When this print statement print('x value inner', x) is executed the innermost scope is with in the method inner_method so the value of x is printed as 16.

When the statement print("x(local)=", x) is executed scope is with in the function my_method so the value of x is printed as 12.

That's all for this topic Namespace And Variable Scope in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Constructor in Python - __init__() function
  2. Class And Object in Python
  3. Interface in Python
  4. Inheritance in Python
  5. Method Overloading in Python

You may also like-

  1. Changing String Case in Python
  2. Python return Statement With Examples
  3. Python Program to Check Prime Number
  4. Comparing Two Strings in Python
  5. How to Sort ArrayList of Custom Objects in Java
  6. Deque Implementation in Java Using Doubly Linked List
  7. How to Inject Null And Empty String Values in Spring
  8. YARN in Hadoop

Wednesday, June 8, 2022

Python First Program - Hello World

Once you are done with Python installation first thing you want to do is to write hello world Python program to check if every thing is working as required or not.

Python command line

You can enter the python command line by typing python on command prompt and write your first hello word program there itself to display “Hello World”.

print() function is used here to print "Hello World" on the console.

Python hello world program

By using command line though we are successful in printing “Hello World” and that does verify installation is done without any problem but this way of writing hello world program doesn’t satiate the programmer in you so you can open an editor and write the same line- print(“Hello World”) there and save it as HelloWorld.py where py extension indicates Python file.

Then you can run this program from command line-

F:\NETJS>Python HelloWorld.py
Hello World
If you want to make HelloWorld Python program procedural then you can also write program in HelloWorld.py as follows.
def display():
 print("Hello World")
# call function
display()

Here display() is a function that prints hello world. You can run this program from command line the same way as above.

Python hello world program – Object oriented way

Well if you are looking for a proper object oriented way to write your first python program then you can write a class and method with in that class to display hello world. Then use an instance of the class to call the method.

class HelloWorld:
  # method
  def display(self):
    print("Hello World")
#creating object
obj = HelloWorld()
#calling method
obj.display()

Output

Hello World

You can also pass an argument to method.

class HelloWorld:
  # method
  def display(self, name):
    print("Hello World", name)
#creating object
obj = HelloWorld()
#calling method
obj.display("netjs")

Output

Hello World netjs

That's all for this topic Python Hello World program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Functions in Python
  2. Class And Object in Python
  3. self in Python
  4. Interface in Python
  5. Python Conditional Statement - if, elif, else Statements

You may also like-

  1. String Slicing in Python
  2. Magic Methods in Python With Examples
  3. Operator Overloading in Python
  4. List in Python With Examples
  5. Statement Interface in Java-JDBC
  6. Conditional Operators in Java With Examples
  7. Insertion Sort Program in Java
  8. Spring MVC File Upload (Multipart Request) Example

Saturday, June 4, 2022

self in Python

In this post we’ll try to understand what is self in Python along with usage examples.

self variable

When you create a new instance of the class, for example-

obj = MyClass() 

a new object is created with its own memory and reference to that object is assigned to the variable obj.

self in Python is also a reference to the current object and it is similar to this in Java and C++. By using self you can access the attributes and methods of a class in python.

Following Python example clarifies how self refers to the current object.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def display_data(self):
    print(self.name)
    print(self.age)

person1 = Person('John', 40)
person1.display_data()
person2 = Person('Jessica', 32)
person2.display_data()

Output

John
40
Jessica
32

As you can see from the output when displayData() method is called on the object person1 it displays the data person1 object is initialized with i.e. self is referring to the person1 object. When displayData() method is called on the object person2 it displays the data person2 object is initialized with i.e. self is referring to the person2 object.

Even in the __init__() function first argument is 'self'. When the constructor is called for initializing the object after it's creation object reference is passed to the first argument (self) of the constructor.

self is not a keyword in Python

All the methods in a class including __init__() must use self as the first parameter but naming this parameter "self" is more of a convention. In Python, self is not a reserved keyword, you can actually use any name as the first parameter of a method though that is not advisable.

Conventionally this parameter is called self in Python and that makes the code more readable.

Why self is not passed in method call

You would have observed in the above example that method call doesn’t include self as a parameter even though method definition does include self as parameter.

Method definition has self as parameter-

def display_data(self):

but when the method is called it is not passed-

person1.display_data()

To understand why method call still works you need to know a little bit about functions and methods in Python.

When you write any def statement with in a class it is a function definition which can be accessed using class name.

A method is a function that belongs to an object.

For example on printing the type of the following statements-

# method call using class name
print(type(Person.display_data))
# method call using object
print(type(person1.display_data))

Output is-

<class 'function'>
<class 'method'>

Coming back to the question how method is called with out an argument. In Python when you call a method using an object, that instance object is passed as the first argument of the function. So a method call person1.display_data() internally becomes Person.display_data(person1) and that person1 reference is assigned to self.

That's all for this topic self in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Class And Object in Python
  2. Name Mangling in Python
  3. Namespace And Variable Scope in Python
  4. Global Keyword in Python With Examples
  5. Python String join() Method

You may also like-

  1. Operator Overloading in Python
  2. Multiple Inheritance in Python
  3. Python Generator, Generator Expression, Yield Statement
  4. Ternary Operator in Python
  5. Java Collections Interview Questions And Answers
  6. Why no Multiple Inheritance in Java
  7. Check if Given String or Number is a Palindrome Java Program
  8. Spring Web MVC Tutorial

Magic Methods in Python With Examples

In Python there are predefined special methods that follow the convention of having method names suffixed and prefixed with double underscores for example __init__(). These special methods are also known as magic methods in Python and also as Dunders (Double UNDERscores).


Python magic methods

These built in methods in Python are known as magic methods as these methods are called automatically to execute the functionality as required by the performed action.

For example when you create an object of a class magic methods __new__() and __init__() are called internally;

  • __new__() is called to create a new instance of class.
  • __init__() is called to initialize the created object.

Another example of magic method is when you add two numbers i.e. a + b, internally __add__() method is called to execute that functionality. More specifically when you write a + b magic method is called internally as a.__add__(b).

Usage of magic methods in Python

Magic methods can be overridden in your class to change the default functionality and fashion these methods as per your custom object needs.

Using magic methods you can do operator overloading in Python. By overriding the corresponding magic method a class can define its own behavior with respect to language operators. For example magic method for multiplication operator (*) is __mul__() so you can overload * operator by overriding __mul__() method in your class.

Available magic methods in Python

There are many magic methods in Python which are called automatically when object is initialized, when object is destroyed, for binary operators, for unary operators, for compound assignment operators, for representing object as string and many mores. We’ll see some of the most used magic methods in this section along with examples of those magic methods.

Magic methods for basic object customization

Magic Method Description
__new__(cls[, ... ])Called to create a new instance of class cls.
__init__(self [, ... ])Called to initialize the object after it is created. This method is called after the instance has been created (by __new__()), but before it is returned to the caller.
__del__(self )Called when the instance is about to be destroyed.

__init__() and __new__() method Python example

In reality most probably __init__() will be the most used magic method for you where as you will explicitly use __new__() method very rarely.

class Person:
  def __new__(cls, x, y):
    print('__new__ called to create object')
    # return created instance
    return super().__new__(cls)
  def __init__(self, name, salary):
    print('__init__ called for object initialization')
    self.name = name
    self.salary = salary

obj1 = Person('John', 4500)
obj2 = Person('Natasha', 6000)

Output

__new__ called to create object
__init__ called for object initialization
__new__ called to create object
__init__ called for object initialization

Magic methods for string representation of an object

Magic Method Description
__repr__(self )Called by the repr() built-in function to compute the “official” string representation of an object.
__str__(self )Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object.
__bytes__(self )Called by bytes to compute a byte-string representation of an object. This should return a bytes object.
__format__(self, format_spec)Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method, to produce a “formatted” string representation of an object.

__str__() magic method Python example

class Person:
  def __init__(self, name, salary):
    print('__init__ called for object initialization')
    self.name = name
    self.salary = salary
  def __str__(self):
    return "Name - " + self.name + " Salary - " + str(self.salary)

obj1 = Person('John', 4500)
obj2 = Person('Natasha', 6000)
print(obj1)
print(obj2)

Output

__init__ called for object initialization
__init__ called for object initialization
Name - John Salary - 4500
Name - Natasha Salary – 6000

Magic methods for arithmetic operators

Operator Magic Method Description
+__add__(self, other)Additive operator
-__sub__(self, other)Subtraction operator
*__mul__(self, other)Multiplication operator
/__truediv__(self, other)Division with fractional result
%__mod__(self, other)Remainder operator
//__floordiv__(self, other)Division with integer result, discarding any fractional part
**__pow__(self, other)Return a to the power b, for a and b numbers.
@__matmul__(self, other)Matrix Multiplication. Available from version 3.5

Overloading ‘*’ operator in Python

class Point:
  def __init__(self, x):
    self.x = x
  #overriding magic method
  def __mul__(self, other):
    return self.x * other.x

p1 = Point(12)
p2 = Point(5)
print(p1*p2)

Output

60

Magic methods for Comparison operators

Operator Magic Method Description
<__lt__(self, other)less than
<=__le__(self, other)less than or equal to
==__eq__(self, other)equal to
!=__ne__(self, other)not equal to
>__gt__(self, other)greater than
>=__ge___(self, other)greater than or equal to

Magic methods for compound assignment operators

Operator Magic Method Description
+=__iadd__(self, other)Addition assignment
–=__isub__(self, other)Subtraction assignment
*=__imul__(self, other)Multiplication assignment
/=__itruediv__(self, other)Division assignment
%=__imod__(self, other)Modulus assignment
//=__ifloordiv__(self, other)Division with integer result, discarding any fractional part
**=__ipow__(self, other)Return a to the power b, for a and b numbers.
@=__imatmul__(self, other)Matrix Multiplication. Available from version 3.5

Magic methods for unary operators

Operator Magic Method Description
+__pos__(self, other)Unary plus operator; indicates positive value
-__neg__(self, other)Unary minus operator; negates an expression
~__invert__(self, other)Returns the bitwise inverse of the number

Overloading comparison operator (>) in Python

class Person:
  def __init__(self, name, salary):
    self.name = name
    self.salary = salary
  #overriding magic method
  def __gt__(self, other):
    return self.salary > other.salary

obj1 = Person('John', 4500)
obj2 = Person('Natasha', 6000)
print(obj1.name, 'earns more than', obj2.name, '-', obj1 > obj2)

Output

John earns more than Natasha - False

Magic methods for container types

If you want your object to emulate container types (List, tuples) then you can override one of the following magic methods for container types.

Magic Method Description
__len__(self )Called to implement the built-in function len() which returns the length of the container.
__getitem__(self, key)To implement behavior for accessing an item using self[key] notation.
__setitem__(self, key, value)To implement behavior to set an item value using self[key]=value notation.
__delitem__(self, key)To implement behavior to delete an item using del self[key] notation.
__iter__(self )This method is called when an iterator is required for a container.
__reversed__(self )To implement reverse iteration.
__contains__(self, item)To implement membership test operators. Should return true if item is in self, false otherwise.

Overloading len magic method in Python

In the following example class overrides __len__() magic method to return the number of transactions using Account object.

class Account:
  def __init__(self, name, acct_num):
    self.name = name
    self.acct_num = acct_num
    #list to add transactions
    self.transactions = []

  def withdraw(self, amount):
    print('Withdrawing amount for ', self.acct_num)
    self.transactions.append(amount)

  def deposit(self, amount):
    print('Depositing amount for ', self.acct_num)
    self.transactions.append(amount)
        
  #oveririding len magic method
  def __len__(self):
    return len(self.transactions)

pa = Account('Ian', 1001)
pa.withdraw(100)
pa.deposit(500)
pa.withdraw(50)
# Using len method with custom object
print('Total Number of Transactions in account- ', len(pa))

Output

Withdrawing amount for  1001
Depositing amount for  1001
Withdrawing amount for  1001
Total Number of Transactions in account-  3

That's all for this topic Magic Methods in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Passing Object of The Class as Parameter in Python
  2. Abstract Class in Python
  3. Global Keyword in Python With Examples
  4. Multiple Inheritance in Python
  5. Namespace And Variable Scope in Python

You may also like-

  1. Python String split() Method
  2. Python assert Statement
  3. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  4. Convert String to int in Python
  5. LinkedHashMap in Java With Examples
  6. Object Creation Using new Operator in Java
  7. Benefits, Disadvantages And Limitations of Autowiring in Spring
  8. Data Locality in Hadoop

Friday, February 4, 2022

Python Installation on Windows

In this post we’ll see how to install Python 3 on Windows. There are two versions of Python- Python 2 and Python 3 so the first question when you start learning Python is which release to go for, Python 2 or Python 3?

Well if you are just starting to learn and there is no old Python project to worry about the compatibility then better to go with release 3 as the final Python 2.x version 2.7 release came out in mid-2010 and the 2.x branch will see no new major releases after that so Pyhton 2.x is legacy. On the other hand Python 3.x is under active development and has stable relases over the years. So, Python 3.x is the present and future of the language.

To get more information about the differences between Python 2 and Python 3, refer the wiki page- https://wiki.python.org/moin/Python2orPython3

Installing Python 3 on Windows

To download Python go to https://www.python.org/ and select Downloads – Windows. That will take you to the page where you can download the Python installer for the current release.

installing python

Current stable release is Python 3.7.3 so click on the “Download Windows x86-64 executable installer” under the stable release to download the executable file (python-3.7.3-amd64.exe).

installing python windows

Once the installer is downloaded click on the downloaded installer to start the Python installation setup.

In the installation set up window-

  • Install launcher for all users
  • Check Add Python 3.x to PATH

Click "Install Now" link to start the Python installation.

Once the download is completed you can click on windows start button to look for the Python installation by going to applications under letter P.

Click on Python 3.x (64 bit) to open command line.

Alternatively you can go to Command Prompt and check for the installation by typing command python –version. It displays the installed version of the python.

You can enter the python command line by typing python and write your first hello word program there itself to display “Hello World”.

Python hello world

You can also use Python IDLE which is the graphical IDE for Python. In the menu you can see an option for IDLE.

Python IDLE

That's all for this topic Python Installation on Windows. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Functions in Python
  2. Python for Loop With Examples
  3. Inheritance in Python
  4. Name Mangling in Python
  5. Method Overriding in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Strings in Python With Method Examples
  3. Multiple Inheritance in Python
  4. Class And Object in Python
  5. How LinkedList Class Works Internally in Java
  6. Race Condition in Java Multi-Threading
  7. Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example
  8. Introduction to Hadoop Framework

Friday, December 18, 2020

Class And Object in Python

Python being an object oriented programming language works on the concept of creating classes and using objects of the class to access the properties and methods defined by the class.

What is a class

In object oriented programming class defines a new type. Class encapsulates data (variables) and functionality (methods) together. Once a class is defined it can be instantiated to create objects of that class. Each class instance (object) gets its own copy of attributes for maintaining its state and methods for modifying its state.

You can create multiple class instances, they all will be of the same type (as defined by the class) but they will have their own state i.e. different values for attributes.

Thursday, December 17, 2020

Constructor in Python - __init__() function

Constructor is a special method provided to initialize objects (assign values to its data members) when they are created. In Python __init__() special method is the constructor and this method is always called when an object is created.

Syntax of init() in Python

First argument in __init__() method is always self. Constructor may or may not have other input parameters i.e. other input parameters are optional.

def __init__(self, input_parameters):
 #initialization code
 ....
 ....

Saturday, November 21, 2020

Name Mangling in Python

In Python there are no explicit access modifiers so you can’t mark a class member as public/private. Then the question is how to restrict access to a variable or method outside the class, if required. Class member can be made private (Close to private actually) using a process called name mangling in Python.


Name mangling (Making member private)

In Python name mangling process any identifier with at least two leading underscores, at most one trailing underscore is textually replaced with _classname__identifier where classname is the current class name. For example if there is a variable __var it is rewritten by the Python interpreter in the form _classname__var.

Since the name of any such class member (with at least two leading underscores, at most one trailing underscore) changes internally thus it can’t be accessed using the given name. That is the closest Python goes for making a class member private.

Python Name mangling example

Let’s try to clarify name mangling process with examples.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

  def display(self):
    print(self.name)
    print(self.__age)

person = Person('John', 40)
#accessing using class method
print('Displaying values using class method')
person.display()
#accessing directly from outside
print('Trying to access variables from outside the class ')
print(person.name)
print(person.__age)

Output

Displaying values using class method
John
40
Traceback (most recent call last):
File "F:/NETJS/NetJS_2017/Python/Test/Person.py", line 21, in <module>
Trying to access variables from outside the class 
John
    print(person.__age)
AttributeError: 'Person' object has no attribute '__age'

As you can see variable __age (having two leading underscores) is not accessible from outside the class. Using a method with in the class it can still be accessed.

Same way for a method with two leading underscores.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

  def __displayAge(self):
    print(self.name)
    print(self.__age)

person = Person('John', 40)
person.__displayAge()

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Person.py", line 15, in <module>
    person.__displayAge()
AttributeError: 'Person' object has no attribute '__displayAge'

As you can see method is not accessible from outside the class.

How does name change in Name mangling

If you want to verify the rewriting of name in Python name mangling process you can do so using the dir() function.

When a class object is passed as an argument to dir() function, it returns a list of valid attributes for that object.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

person = Person('John', 40)
print(dir(person))

Output

['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', 
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', 
'__str__', '__subclasshook__', '__weakref__', 'name']

From the output of dir() function for Person object you can see that the __age is rewritten as _Person__age.

Name mangling and method overriding

As per Python docs stated objective of name mangling is to avoid name clashes of names with names defined by subclasses. Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls.

For example consider the following scenario where Parent class is subclassed and there is an overridden method test is the Child class too. From the constructor of Parent class there is a call to test method- self.test()

class Parent:
  def __init__(self):
    print('in init')
    self.test()
  def test(self):
    print('In Parent test method')

class Child(Parent):
  def test(self):
    print('In Child test method')

obj = Child()
obj.test()

Output

in init
In Child test method
In Child test method

As you can see Child test method is getting called both of the times. To avoid that name clash you can create a private copy of the original method.

class Parent:
  def __init__(self):
    print('in init')
    self.__test()
  def test(self):
    print('In Parent test method')

  # private copy
  __test = test

class Child(Parent):
  def test(self):
    print('In Child test method')

obj = Child()
obj.test()

Output

in init
In Parent test method
In Child test method

Accessing name mangled class members

As already stated Python name mangling process rewrites the member name by adding _classname to the member. Thus it is still possible to access the class member from outside the class by using the rewritten name. That is why it is said that Name mangling is the closest to private not exactly private.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

  def display(self):
    print(self.name)
    print(self.__age)

person = Person('John', 40)
print('Trying to access variables from outside the class ')
print(person.name)
print(person._Person__age)

Output

Trying to access variables from outside the class 
John
40

As you can see private class member is accessed from outside the class by using the name mangled form _ClassName__var.

That's all for this topic Name Mangling in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Installation on Windows
  2. Encapsulation in Python
  3. Method Overriding in Python
  4. Multiple Inheritance in Python
  5. Python for Loop With Examples

You may also like-

  1. Passing Object of The Class as Parameter in Python
  2. Local, Nonlocal And Global Variables in Python
  3. Python count() method - Counting Substrings
  4. Python Functions : Returning Multiple Values
  5. Marker Interface in Java
  6. Functional Interfaces in Java
  7. Difference Between Checked And Unchecked Exceptions in Java
  8. Race Condition in Java Multi-Threading