0% found this document useful (0 votes)
19 views7 pages

Python Classes namespace inheritance

Uploaded by

Vidhya Gopinath
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
19 views7 pages

Python Classes namespace inheritance

Uploaded by

Vidhya Gopinath
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 7

Python Classes/Objects

Python is an object oriented programming language.


Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.

1. Create a Class
To create a class, use the keyword class:
Example:
Create a class named MyClass, with a property named x:

class MyClass:
x=5
2.Create Object
Now we can use the class named MyClass to create objects:

Example
Create an object named p1, and print the value of x:

p1 = MyClass()
print(p1.x)
3.The __init__() Function
The examples above are classes and objects in their simplest form, and are not really useful in
real life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being
initiated.
Use the __init__() function to assign values to object properties, or other operations that are
necessary to do when the object is being created:

Example
Create a class named Person, use the __init__() function to assign values for name and age:

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

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being used to create
a new object.

4.The __str__() Function


The __str__() function controls what should be returned when the class object is represented
as a string.
If the __str__() function is not set, the string representation of the object is returned:

Example
The string representation of an object WITH the __str__() function:

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

def __str__(self):
return f"{self.name}({self.age})"

p1 = Person("John", 36)

print(p1)
5.Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.
Let us create a method in the Person class:

Example
Insert a function that prints a greeting, and execute it on the p1 object:

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

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()
6.The self Parameter
The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class:

Example
Use the words mysillyobject and abc instead of self:

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

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()
Modify Object Properties
You can modify properties on objects like this:

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

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)

p1.age = 40

print(p1.age)
#Set the age of p1 to 40:

p1.age = 40
Delete Object Properties
You can delete properties on objects by using the del keyword:

Example
Delete the age property from the p1 object:

del p1.age
INHERITANCE:
Inheritance is the capability of one class to derive or inherit the properties from another class.
Benefits of inheritance are:
Inheritance allows you to inherit the properties of a class, i.e., base class to another, i.e.,
derived class. The benefits of Inheritance in Python are as follows:
 It represents real-world relationships well.
 It provides the reusability of a code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.
 It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.
 Inheritance offers a simple, understandable model structure.
 Less development and maintenance expenses result from an inheritance.

Inheritance Syntax
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}

# A Python program to demonstrate inheritance

# Base or Super class. Note object in bracket.


# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"

class Person(object):

# Constructor
def __init__(self, name):
self.name = name

# To get name
def getName(self):
return self.name

# To check if this person is an employee


def isEmployee(self):
return False

# Inherited or Subclass (Note Person in bracket)


class Employee(Person):

# Here we return true


def isEmployee(self):
return True

# Driver code
emp = Person("Geek1") # An Object of Person
print(emp.getName(), emp.isEmployee())

emp = Employee("Geek2") # An Object of Employee


print(emp.getName(), emp.isEmployee())

Output:
Geek1 False
Geek2 True
Namespaces and Scope in Python
A namespace is a system that has a unique name for each and every object in Python.
An object might be a variable or a method. Python itself maintains a namespace in the
form of a Python dictionary

the role of a namespace is like a surname.

Name (which means name, a unique identifier) + Space(which talks something related
to scope)

The built-in namespace encompasses the global namespace and the global namespace
encompasses the local namespace.

The lifetime of a namespace :


A lifetime of a namespace depends upon the scope of objects, if the scope of an object
ends, the lifetime of that namespace comes to an end. Hence, it is not possible to access
the inner namespace’s objects from an outer namespace.

Example:
# var1 is in the global namespace
var1 = 5
def some_func():

# var2 is in the local namespace


var2 = 6
def some_inner_func():

# var3 is in the nested local


# namespace
var3 = 7
EXAMPLE:
# Python program processing
# global variable

count = 5
def some_method():
global count
count = count + 1
print(count)
some_method()

output: 6

** if two function having same name belonging to two different modules at a time in some other
module then that might create nameclash.

1. firstmodule.py

def display(a,b):
return a+b
2. secondmodule.py
def display(a,b):
return a*b
3.
import firstmodule.py
import secondmodule.py
print(display(10,20))
print(display(5,4))

**error**
4.
import firstmodule.py
import secondmodule.py
print(firstmodule .display(10,20))
print(secondmodule .display(5,4))

output:
30
20

You might also like