StudyLover
  • Home
  • Study Zone
  • Profiles
  • Contact us
  • Sign in
StudyLover Methods
Download
  1. Python
  2. OOP: A Comprehensive Guide
Attributes : 'self' Parameter & Pass statement
OOP: A Comprehensive Guide

Object Methods

Object methods are functions defined within a class. They provide the behavior and functionality of objects created from that class.

Syntax:

Python

class MyClass:

  def __init__(self, attribute1, attribute2):

    self.attribute1 = attribute1

    self.attribute2 = attribute2

 

  def method1(self):

    # Method   implementation

    pass

 

  def method2(self):

    # Method implementation

    pass

self Keyword:

  • The self keyword is used within methods to refer to the current object instance.

  • It allows methods to access and modify the object's attributes.

Types of Methods:

  • Instance methods: Operate on specific object instances.

  • Class methods: Belong to the class itself and can be called without creating an instance. Decorated with @classmethod.

  • Static methods: Don't have access to the instance or class. Decorated with @staticmethod.

Example:

Python

class Person:

  def __init__(self, name, age):

    self.name = name

    self.age = age

 

  def greet(self):

    print(f"Hello, my name is {self.name}.")  

 

  @classmethod

  def create_from_string(cls, person_data):

    name, age = person_data.split(",")

    return cls(name, int(age))

 

person1 = Person("Alice", 30)

person1.greet()  # Output: Hello, my name is Alice.

 

person2_data = "Bob,25"

person2 = Person.create_from_string(person2_data)

person2.greet()  # Output: Hello, my name is Bob.

Best Practices:

  • Use descriptive method names that reflect their functionality.

  • Encapsulate data within classes and access it through methods.

  • Avoid redundant or unnecessary methods.

  • Use appropriate method types (instance, class, static) based on their purpose.

By understanding object methods and their usage, you can effectively design and implement object-oriented programs in Python.

Modifying Object Properties in Python

To modify the properties (attributes) of an object in Python, you can directly access and assign new values to them.

Syntax:

Python

object_name.property_name = new_value

Example:

Python

class Person:

  def __init__(self, name, age):

    self.name = name

    self.age = age

 

person = Person("Alice", 30)

 

# Modifying the age property

person.age = 31

 

print(person.age)  # Output: 31

Key Points:

  • Use the dot notation to access object properties.

  • Assign new values directly to the properties.

  • Be mindful of data types. Ensure the new value is compatible with the property's type.

Additional Considerations:

  • Private Attributes: If you want to make attributes private, prefix them with a double underscore (__). This prevents direct access from outside the class. However, they can still be accessed indirectly using getter and setter methods.

  • Immutable Objects: If the property is an immutable object (like a string or number), assigning a new value will create a new object.

  • Data Validation: Consider implementing validation logic to ensure that assigned values are valid and within acceptable ranges.

Example with Private Attributes:

Python

class Person:

  def __init__(self, name, age):

    self.__name = name

    self.__age = age

 

  def get_name(self):

    return self.__name

 

  def set_name(self, name):

    self.__name = name  

# Accessing and modifying the name property

person.set_name("Bob")

print(person.get_name())  # Output: Bob

By understanding these concepts, you can effectively modify object properties in Python to update the state of your objects.

 

Adding Methods to Python Classes

Methods are functions defined within a class that provide the behavior and functionality of objects created from that class. They can be used to:

  • Perform actions: Execute specific tasks related to the object's state.

  • Access or modify attributes: Get or set the values of object properties.

  • Implement custom logic: Define the behavior of the object.

Syntax:

Python

class MyClass:

  def __init__(self, attribute1, attribute2):

    self.attribute1 = attribute1

    self.attribute2 = attribute2

 

  def method1(self):

    # Method implementation

 

  def method2(self):

    # Method implementation

Example:

Python

class Person:

  def __init__(self, name, age):

    self.name = name

    self.age = age

 

  def greet(self):

    print(f"Hello, my name is {self.name}.")  

 

  def get_age(self):

    return self.age

Key Points:

  • Methods are defined within the class body.

  • They take the self parameter as the first argument, which refers to the current object instance.

  • Methods can access and modify the object's attributes.

  • You can define any number of methods within a class.

Best Practices:

  • Use descriptive method names that reflect their functionality.

  • Encapsulate data within classes and access it through methods.

  • Avoid redundant or unnecessary methods.

  • Consider using property decorators for simple getter and setter methods.

By understanding methods and their usage, you can effectively design and implement object-oriented programs in Python.

Iterators in Python

Iterators are objects that provide a way to access elements of a sequence one by one. They are used to iterate over collections like lists, tuples, dictionaries, and sets.

Creating Iterators

Python provides built-in iterators for many data structures. You can also create custom iterators by implementing the __iter__ and __next__ methods.

Python

class MyIterator:

    def __init__(self, data):

        self.data = data

        self.index = 0

 

    def __iter__(self):

        return self

 

    def __next__(self):

        if self.index < len(self.data):  

            value = self.data[self.index]

            self.index += 1

            return value

        else:

            raise StopIteration  

Using Iterators

You can use the for loop to iterate over an iterable object:

Python

my_list = [1, 2, 3]

for item in my_list:

    print(item)

Built-in Functions

Python provides built-in functions that work with iterators:

  • iter(): Creates an iterator from an iterable object.

  • next(): Retrieves the next element from an iterator.

  • enumerate(): Creates an iterator that returns tuples containing the index and value of each element.

  • zip(): Creates an iterator that aggregates elements from multiple iterables.

Example:

Python

my_list = [1, 2, 3]

my_iterator = iter(my_list)

 

print(next(my_iterator))  # Output: 1

print(next(my_iterator))  # Output: 2

print(next(my_iterator))  

 

  # Output: 3  

 

# Using a for loop

for item in my_list:

    print(item)

Key Points:

  • Iterators provide a unified way to access elements of different data structures.

  • The __iter__ method returns the iterator object itself.

  • The __next__ method returns the next element in the sequence.

  • The StopIteration exception is raised when there are no more elements.

Looping Through an Iterator in Python

Iterators are objects that provide a way to access elements of a sequence one by one. You can use the for loop to iterate over an iterator:

Python

my_list = [1, 2, 3]

my_iterator = iter(my_list)

 

for item in my_iterator:

    print(item)

This code will output:

1

2

3

Key Points:

  • The for loop automatically calls the __iter__ method on the iterable object to get an iterator.

  • It then repeatedly calls the __next__ method on the iterator until a StopIteration exception is raised.

  • The for loop handles the iteration process, making it convenient to work with iterators.

Example with a Custom Iterator:

Python

class MyIterator:

    def __init__(self, data):

        self.data = data

        self.index = 0

 

    def __iter__(self):

        return self

 

    def __next__(self):  

 

        if self.index < len(self.data):

            value = self.data[self.index]

            self.index += 1

            return value

        else:

            raise StopIteration  

 

my_iterator = MyIterator([1, 2, 3])

 

for item in my_iterator:

    print(item)

This code will output:

1

2

3

By understanding how to loop through iterators, you can effectively work with various data structures and perform operations on their elements.

 


To delete object properties in Python, you can use the del keyword.

Syntax:

Python

del object_name.property_name

Example:

Python

class Person:

  def __init__(self, name, age):

    self.name = name

    self.age = age

 

person = Person("Alice", 30)

 

del person.age

print(person.age)  # Output: AttributeError: 'Person' object has no attribute 'age'

In this example, the del keyword is used to delete the age property from the person object. After deletion, attempting to access the age property raises an AttributeError.

Important Notes:

  • Deleting an object property permanently removes it from the object's attributes.

  • If you need to temporarily hide or modify a property, consider using a getter and setter method instead of deletion.

  • Be cautious when deleting properties, as it can affect the object's behavior and functionality.

 

 

To delete objects in Python, you can use the del keyword. This removes the object from memory, making its reference invalid.

Syntax:

Python

del object_name

Example:

Python

class Person:

  def __init__(self, name, age):

    self.name = name

    self.age = age

 

person = Person("Alice", 30)

 

del person

 

# Trying to access the object after deletion will raise an error

print(person.name)  # Output: AttributeError: 'Person' object has no attribute 'name'

Important Notes:

  • Deleting an object does not automatically delete its attributes. If the attributes are references to other objects, those objects may still exist in memory.

  • Deleting an object can have cascading effects if it's referenced by other objects.

  • Use caution when deleting objects to avoid unexpected behavior or errors.

Additional Considerations:

  • Garbage Collection: Python's garbage collector automatically reclaims memory for objects that are no longer referenced. However, deleting objects explicitly can help manage memory usage.

  • Custom Destructors: While Python doesn't have explicit destructors like some other languages, you can implement custom cleanup logic using the __del__ method. However, relying on __del__ for resource management is generally discouraged due to its unpredictable nature.

 

Attributes 'self' Parameter & Pass statement
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website