Course Topics
Python Basics Introduction and Setup Syntax and Indentation Comments and Documentation Running Python Programs Exercise Variables and Data Types Variables and Assignment Numbers (int, float, complex) Strings and Operations Booleans and None Type Conversion Exercise Operators Arithmetic Operators Comparison Operators Logical Operators Assignment Operators Bitwise Operators Exercise Input and Output Getting User Input Formatting Output Print Function Features Exercise Control Flow - Conditionals If Statements If-Else Statements Elif Statements Nested Conditionals Exercise Control Flow - Loops For Loops While Loops Loop Control (break, continue) Nested Loops Exercise Data Structures - Lists Creating and Accessing Lists List Methods and Operations List Slicing List Comprehensions Exercise Data Structures - Tuples Creating and Accessing Tuples Tuple Methods and Operations Tuple Packing and Unpacking Exercise Data Structures - Dictionaries Creating and Accessing Dictionaries Dictionary Methods and Operations Dictionary Comprehensions Exercise Data Structures - Sets Creating and Accessing Sets Set Methods and Operations Set Comprehensions Exercise Functions Defining Functions Function Parameters and Arguments Return Statements Scope and Variables Lambda Functions Exercise String Manipulation String Indexing and Slicing String Methods String Formatting Regular Expressions Basics Exercise File Handling Opening and Closing Files Reading from Files Writing to Files File Modes and Context Managers Exercise Error Handling Understanding Exceptions Try-Except Blocks Finally and Else Clauses Raising Custom Exceptions Exercise Object-Oriented Programming - Classes Introduction to OOP Creating Classes and Objects Instance Variables and Methods Constructor Method Exercise Object-Oriented Programming - Advanced Inheritance Method Overriding Class Variables and Methods Static Methods Exercise Modules and Packages Importing Modules Creating Custom Modules Python Standard Library Installing External Packages Exercise Working with APIs and JSON Making HTTP Requests JSON Data Handling Working with REST APIs Exercise Database Basics Introduction to Databases SQLite with Python CRUD Operations Exercise Final Project Project Planning Building Complete Application Code Organization Testing and Debugging Exercise

Instance Variables and Methods

Introduction

  • Why this topic matters: Understanding instance variables and methods is crucial to creating object-oriented programs in Python. They enable you to store data specific to each object and define behaviors that objects can perform.
  • What you'll learn: In this lesson, we will explore what instance variables and methods are, learn how to create them, and examine practical examples, common issues, solutions, best practices, and key takeaways.

Core Concepts

  • Instance Variables: These are variables that belong to an instance of a class. Each object created from the class will have its own set of instance variables with unique values.

Example:
```python
class Car:
def init(self, color):
self.color = color

my_car = Car("red")
your_car = Car("blue")
print(my_car.color) # Output: red
print(your_car.color) # Output: blue
```
- Methods: These are functions that belong to a class and operate on the instance variables of that class. They can be called by accessing the method name through an object instance.

Example:
```python
class Car:
def init(self, color):
self.color = color

  def paint(self, new_color):
      self.color = new_color

my_car = Car("red")
my_car.paint("blue")
print(my_car.color) # Output: blue
```

Practical Examples

  • Create a class for a Person with instance variables name and age, and methods to set and get these values.
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def set_name(self, new_name):
        self.name = new_name

    def get_name(self):
        return self.name

    def set_age(self, new_age):
        if new_age > 0:
            self.age = new_age

    def get_age(self):
        return self.age

john = Person("John", 25)
print(f"{john.get_name()} is {john.get_age()} years old.")

Common Issues and Solutions (CRITICAL SECTION)

NameError

What causes it: Attempting to access an instance variable or method that doesn't exist in the current scope or class.

class Car:
    def __init__(self, color):
        self.color = color

    def paint(self, new_color):
        self.color = new_color

my_car = Car("red")
print(my_car.unassigned_variable)  # NameError: name 'unassigned_variable' is not defined

Solution: Define the instance variable or method in the class.

class Car:
    def __init__(self, color):
        self.color = color
        self.num_wheels = 4

    def paint(self, new_color):
        self.color = new_color

Why it happens: The variable or method was not properly defined within the class's scope.

How to prevent it: Make sure all necessary instance variables and methods are defined in the class before trying to access them.

AttributeError

What causes it: Attempting to access an instance variable that doesn't exist for the current object or a method of a different class with the same name.

class Car:
    def __init__(self, color):
        self.color = color

class Truck:
    pass

my_car = Car("red")
print(my_car.num_wheels)  # AttributeError: 'Car' object has no attribute 'num_wheels'

Solution: Define the missing instance variable in the class or create a method that returns the desired value if it is calculated dynamically.

class Car:
    def __init__(self, color):
        self.color = color

    def num_wheels(self):
        return 4

my_car = Car("red")
print(my_car.num_wheels())  # Output: 4

Why it happens: The object instance does not have the specific instance variable or the method name is being used for a different class with the same name.

How to prevent it: Double-check that you are using the correct instance variable or method for the object and ensure there are no conflicting names among classes.

TypeError

What causes it: Assigning an incompatible data type to an instance variable during initialization or modifying its value later on.

class Car:
    def __init__(self, color):
        self.color = color

my_car = Car("red")
my_car.num_wheels = "four"  # TypeError: 'str' object does not support item assignment

Solution: Ensure that the data type assigned to the instance variable is compatible with its expected type.

class Car:
    def __init__(self, color):
        self.color = color
        self.num_wheels = 4

my_car = Car("red")
my_car.num_wheels = 5  # This won't raise a TypeError since int and integer are compatible

Why it happens: The data type being assigned to the instance variable does not match its expected data type, such as assigning a string to an integer variable.

How to prevent it: Use appropriate data types for instance variables, and verify that any user input or external values passed to the class are compatible with the intended data type of the instance variable.

Best Practices

  • Use descriptive names for instance variables and methods.
  • Keep related instance variables and methods within the same class.
  • Document your classes, instance variables, and methods using docstrings.
  • Limit the number of instance variables per class to make the code more manageable.
  • Be mindful of performance considerations when defining methods that are called frequently or involve complex calculations.

Key Takeaways

  • Instance variables store data specific to each object, while methods define behaviors for those objects.
  • Properly define instance variables and methods in your classes to avoid common issues like NameError, AttributeError, and TypeError.
  • Adhere to best practices such as using descriptive names, limiting the number of instance variables, and documenting your code.
  • Continue learning about object-oriented programming concepts in Python to further enhance your skills.