PyAnWin/Python Classes and OOP

From Wikibooks, open books for an open world
Jump to navigation Jump to search

```wikicode

Object-Oriented Programming (OOP) in Python[edit | edit source]

Object-Oriented Programming (OOP) is a programming paradigm that structures programs by bundling related properties and behaviors into individual objects. Objects represent components of a system, similar to an assembly line where each step processes materials to create a finished product. An object contains data (like raw materials) and behavior (like assembly line actions).

Defining a Class: The Blueprint[edit | edit source]

A class serves as a blueprint for creating objects. To define a class, use the `class` keyword.

class MyClass:
    x = 5


p1 = MyClass()
print(p1.x)


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

p1 = Person("John", 36)
print(p1.name)



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)



class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def myfunc(self):
        print(f"Hello, my name is {self.name}")

p1 = Person("John", 36)

```

Creating Objects (Instances)[edit | edit source]

Instantiate a class to create objects.

Example: ```python p1 = MyClass() print(p1.x) ```

The `__init__()` Function[edit | edit source]

The `__init__()` function initializes object properties. It's executed when an object is created.

Customizing String Representation (`__str__()` Function)[edit | edit source]

Control how an object is represented as a string.

Object Methods[edit | edit source]

Remember, OOP allows you to model real-world entities and their interactions. Dive deeper into classes, inheritance, and more to unlock the full power of Python! 🐍