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

Python Classes and Object-Oriented Basics

Uploaded by

Vidhya Gopinath
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views7 pages

Python Classes and Object-Oriented Basics

Uploaded by

Vidhya Gopinath
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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
[Link] 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)
[Link] __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):
[Link] = name
[Link] = age

p1 = Person("John", 36)

print([Link])
print([Link])
Note: The __init__() function is called automatically every time the class is being used to create
a new object.

[Link] __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):
[Link] = name
[Link] = age

def __str__(self):
return f"{[Link]}({[Link]})"

p1 = Person("John", 36)

print(p1)
[Link] 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):
[Link] = name
[Link] = age

def myfunc(self):
print("Hello my name is " + [Link])

p1 = Person("John", 36)
[Link]()
[Link] 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):
[Link] = name
[Link] = age

def myfunc(abc):
print("Hello my name is " + [Link])

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

Example
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def myfunc(self):
print("Hello my name is " + [Link])

p1 = Person("John", 36)

[Link] = 40

print([Link])
#Set the age of p1 to 40:

[Link] = 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 [Link]
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):
[Link] = name

# To get name
def getName(self):
return [Link]

# 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([Link](), [Link]())

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


print([Link](), [Link]())

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. [Link]

def display(a,b):
return a+b
2. [Link]
def display(a,b):
return a*b
3.
import [Link]
import [Link]
print(display(10,20))
print(display(5,4))

**error**
4.
import [Link]
import [Link]
print(firstmodule .display(10,20))
print(secondmodule .display(5,4))

output:
30
20

Common questions

Powered by AI

The self parameter in Python class methods is a reference to the current instance of the class, allowing access to instance attributes and methods. Though it can be named differently, it's conventional to use 'self'. This parameter is pivotal in enabling methods to interact with object data, facilitating encapsulation and object-specific behavior. It allows for method definitions that manipulate attributes of the particular instance with which they are called, central to object-oriented design .

Modifying object properties after instantiation allows for dynamic changes in the object state, which can reflect real-time data or user interactions. However, it also raises potential consistency issues if dependent properties are not updated accordingly. For instance, changing the age property of a Person object from 36 to 40 alters the object’s state post-creation. It's important to consider object integrity and encapsulation when modifying properties to avoid unexpected side effects .

The __str__() method in Python classes defines a string representation of an instance, which is returned when the object is printed or converted to a string. This method enhances usability by providing a human-readable string that summarizes the object state, which is crucial for debugging and logging purposes. For instance, defining __str__() in a class allows the object instances to be displayed in a clear format, like showing the name and age of a Person object as 'John(36)' .

Namespaces in Python logically group identifiers such as variables, functions, and classes to prevent naming conflicts. A namespace ensures that each identifier has a unique context, facilitating code organization. For instance, Python uses separate namespaces for built-in, global, and local scopes, preventing access to local variables from the global scope. This structure is crucial for isolating code segments and handling cases where different modules define functions with identical names .

Overriding methods in a derived class allows for customized behavior that differs from the base class. Instances of the derived class will execute the overridden methods instead of the base ones; this enables polymorphism. For example, if the derived class Employee overrides the isEmployee() method from the base class Person, instances of Employee will return True from isEmployee(), showing differentiated behavior from instances of Person, which return False .

The __init__() method is a special function in Python that is automatically invoked when a new object is created from a class. It is used for initializing the object’s attributes with specific values, thus setting up the initial state of the object. Without it, objects would lack the necessary setup or state, rendering them less useful in practical applications .

Deleting an object property with the 'del' keyword removes the attribute from the object’s namespace, potentially leading to AttributeErrors if the deleted property is accessed later. This operation can make the object state incomplete or inconsistent with its expected usage. For example, deleting the 'age' property of a Person object means that any subsequent attempt to access 'age' will raise an error unless the property is redefined or checked for existence beforehand .

Inheritance in Python facilitates code reusability by allowing new classes to reuse and extend existing code without redundancy. It provides a clear and structured model hierarchy, representing real-world relationships and encouraging maintainable and scalable system architectures. Furthermore, inheritance reduces development and maintenance costs by simplifying code updates; changes made in a base class propagate to all derived classes, demonstrating its transitive nature .

Python uses module namespaces to resolve name clashes. When functions from different modules have the same name, they can still be used without conflict by accessing them through their respective module names. For example, calling firstmodule.display and secondmodule.display differentiates the functions despite identical names. Developers can prevent name clashes by using aliases with 'import as', employing unique function names, or organizing code into well-defined modules and packages .

Global variables manage state at the program level, accessible across functions unless shadowed by local variables. This accessibility makes them useful for maintaining shared states. However, their global nature implies potential for unintended modifications and tight coupling of functions to specific global contexts. For example, incrementing a global count in a function affects all parts of the program using that count, which may lead to unpredictable results or conflicts in larger programs .

You might also like