🔧 AI Nachrichten The Next Terrorist Attack Is Predictable(10.09.2026 um 23:41 Uhr)
🔧 AI Nachrichten Could A.I. Really Kill All Humans?(10.09.2026 um 23:53 Uhr)
🔧 AI Nachrichten Amazon Prime Video Uses A.I. for Lip-Synced Translations(11.09.2026 um 01:56 Uhr)
🔧 AI Nachrichten McClatchy Makes Deep Job Cuts to Newspapers Around the Country(11.09.2026 um 04:25 Uhr)
🔧 AI Nachrichten Law schools tell students to put AI away(07.09.2026 um 16:37 Uhr)
🔧 AI Nachrichten Can Huawei build China’s answer to ASML?(08.09.2026 um 04:57 Uhr)
🔧 AI Nachrichten AI is ushering in an era of mass toe-treading at work(08.09.2026 um 06:00 Uhr)
🔧 AI Nachrichten The Next Terrorist Attack Is Predictable(10.09.2026 um 23:41 Uhr)
🔧 AI Nachrichten Could A.I. Really Kill All Humans?(10.09.2026 um 23:53 Uhr)
🔧 AI Nachrichten Amazon Prime Video Uses A.I. for Lip-Synced Translations(11.09.2026 um 01:56 Uhr)
🔧 AI Nachrichten McClatchy Makes Deep Job Cuts to Newspapers Around the Country(11.09.2026 um 04:25 Uhr)
🔧 AI Nachrichten Law schools tell students to put AI away(07.09.2026 um 16:37 Uhr)
🔧 AI Nachrichten Can Huawei build China’s answer to ASML?(08.09.2026 um 04:57 Uhr)
🔧 AI Nachrichten AI is ushering in an era of mass toe-treading at work(08.09.2026 um 06:00 Uhr)

🔧 Programmierung 🕛 vor 2 Monaten 8 Min Lesezeit
0

Python for Beginners — Part 8: Object-Oriented Python

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

Part 8 of an 8-part beginner-friendly series on learning Python from scratch.



Congratulations — you've made it to the final part!



Everything you've learned — variables, control flow, collections, functions, file I/O, error handling — can be organized into classes and objects. This is object-oriented programming (OOP), and it's how professional Python code is written.



OOP isn't required to write working programs, but it's essential for writing code that scales, is maintainable, and professional. This final article brings everything together.






Classes and Objects



A class is a blueprint for creating objects. An object is an instance of that class. Think of a class like a cookie cutter and objects like the cookies it produces.






Defining a class






CODE
class Person:
pass

# Create an object (instance)
person = Person()
print(person) # <__main__.Person object at 0x...>






class Person: defines a class. person = Person() creates an object from that class.






The __init__ Method and self



The __init__ method runs automatically when you create an object. It's where you initialize the object's data.




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

person = Person("Ramesh", 25)
print(person.name) # Ramesh
print(person.age) # 25






self represents the object itself. When you write self.name = name, you're saying "this object's name attribute equals the name I was given."



Think of it this way:





  • name (parameter) is the input


  • self.name (attribute) is the object's stored data






Creating multiple objects






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

person1 = Person("Ramesh", 25)
person2 = Person("Priya", 23)

print(person1.name, person1.age) # Ramesh 25
print(person2.name, person2.age) # Priya 23






Each object is independent. person1.name is separate from person2.name.






Methods



A method is a function inside a class. Methods operate on the object's data:




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

def greet(self):
return f"Hello, I'm {self.name}"

def have_birthday(self):
self.age += 1

person = Person("Ramesh", 25)
print(person.greet()) # Hello, I'm Ramesh
person.have_birthday()
print(person.age) # 26






Call methods with dot notation: person.greet(). The self parameter is passed automatically — you don't type it.






Instance vs Class Variables



Instance variables are unique to each object. Class variables are shared by all objects of that class:




CODE
class Dog:
species = "Canis familiaris" # Class variable

def __init__(self, name):
self.name = name # Instance variable

dog1 = Dog("Buddy")
dog2 = Dog("Max")

print(dog1.name) # Buddy (unique to dog1)
print(dog2.name) # Max (unique to dog2)
print(Dog.species) # Canis familiaris (shared)
print(dog1.species) # Canis familiaris (accessible via instance too)






Use class variables for data shared by all instances. Use instance variables for data unique to each instance.






Inheritance



Inheritance lets you create a new class based on an existing class. The new class inherits methods and attributes from the parent:




CODE
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
return f"{self.name} makes a sound"

class Dog(Animal):
def speak(self):
return f"{self.name} barks"

class Cat(Animal):
def speak(self):
return f"{self.name} meows"

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak()) # Buddy barks
print(cat.speak()) # Whiskers meows






Dog and Cat inherit from Animal and override the speak() method. This is called method overriding.






Using super()



Call the parent class's method with super():




CODE
class Animal:
def __init__(self, name):
self.name = name

def describe(self):
return f"{self.name} is an animal"

class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent's __init__
self.breed = breed

def describe(self):
parent_desc = super().describe() # Call parent's describe
return f"{parent_desc} and is a {self.breed}"

dog = Dog("Buddy", "Golden Retriever")
print(dog.describe()) # Buddy is an animal and is a Golden Retriever






super() lets you access the parent class without repeating code.






Polymorphism



Polymorphism means "many shapes" — the same function name works differently depending on the object type:




CODE
class Dog:
def speak(self):
return "Woof!"

class Cat:
def speak(self):
return "Meow!"

class Cow:
def speak(self):
return "Moo!"

animals = [Dog(), Cat(), Cow()]

for animal in animals:
print(animal.speak())

# Output:
# Woof!
# Meow!
# Moo!






Each animal speaks differently, but you call the same method. This is polymorphism in action.






Encapsulation



Encapsulation is the idea of bundling data and methods together, and controlling access to them. Python uses naming conventions:





  • public_attribute — accessible from outside (convention)


  • _private_attribute — intended private (convention, not enforced)


  • __really_private — name-mangled, harder to access (enforced)




CODE
class BankAccount:
def __init__(self, balance):
self.__balance = balance # "Private"

def deposit(self, amount):
if amount > 0:
self.__balance += amount

def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount

def get_balance(self):
return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500

# Can't access directly:
# print(account.__balance) # AttributeError (name-mangled)






The double underscore (__) makes the attribute private. Access it through methods instead. This prevents accidental misuse.






Dunder Methods



Dunder methods (double underscore) are special methods Python calls automatically. Here are the most important:






__str__ and __repr__






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

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

def __repr__(self):
return f"Person('{self.name}', {self.age})"

person = Person("Ramesh", 25)
print(str(person)) # Ramesh (25) — human-readable
print(repr(person)) # Person('Ramesh', 25) — for debugging






__str__ is for end users. __repr__ is for developers.






__len__






CODE
class ShoppingCart:
def __init__(self):
self.items = []

def add(self, item):
self.items.append(item)

def __len__(self):
return len(self.items)

cart = ShoppingCart()
cart.add("apple")
cart.add("banana")
print(len(cart)) # 2






Now len(cart) returns the number of items.






__eq__






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

def __eq__(self, other):
return self.name == other.name

person1 = Person("Ramesh")
person2 = Person("Ramesh")
print(person1 == person2) # True (compares names)






Define how == works for your objects.






Properties and Getters/Setters



Properties let you access attributes like data, but with method-like control:




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

@property
def name(self):
return self._name

@name.setter
def name(self, value):
if len(value) > 0:
self._name = value

person = Person("Ramesh")
print(person.name) # Ramesh (getter)
person.name = "Priya" # Setter
print(person.name) # Priya






The @property decorator makes name act like an attribute but run validation code.






Practical Examples






Example 1: User class






CODE
class User:
def __init__(self, username, email):
self.username = username
self.email = email
self.created_at = datetime.now()

def __str__(self):
return f"User({self.username})"

def change_email(self, new_email):
if "@" in new_email:
self.email = new_email
else:
raise ValueError("Invalid email")

user = User("ramesh", "[email protected]")
print(user) # User(ramesh)
user.change_email("[email protected]")









Example 2: Inheritance with Bank Accounts






CODE
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance

def deposit(self, amount):
self.balance += amount

class SavingsAccount(Account):
def __init__(self, owner, balance, interest_rate):
super().__init__(owner, balance)
self.interest_rate = interest_rate

def apply_interest(self):
self.balance *= (1 + self.interest_rate)

savings = SavingsAccount("Ramesh", 1000, 0.05)
savings.deposit(500)
savings.apply_interest()
print(savings.balance) # 1575.0









Example 3: Polymorphism with shapes






CODE
class Shape:
def area(self):
raise NotImplementedError

class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.14 * self.radius ** 2

class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height

def area(self):
return self.width * self.height

shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(f"Area: {shape.area()}")

# Output:
# Area: 78.5
# Area: 24









Why This Matters



OOP is how professional code is organized. Without it, programs become tangled messes of functions and variables. With OOP, you group related data and behavior together into classes, making code:





  • Reusable — inheritance lets you extend existing code


  • Maintainable — encapsulation hides complexity


  • Scalable — polymorphism lets you add new types easily


  • Clear — objects represent real-world concepts



The most common beginner mistakes:




  • Forgetting self in methods

  • Confusing __init__ (constructor) with class definition

  • Not using inheritance when it makes sense

  • Overcomplicating with too many classes (start simple)

  • Breaking encapsulation with direct attribute access






Your Journey is Complete



You've now learned:





  1. Syntax and basics (Parts 1–2)


  2. Working with text and logic (Parts 3–4)


  3. Organizing data (Part 5)


  4. Organizing code (Part 6)


  5. Working in the real world (Part 7)


  6. Professional code structure (Part 8: OOP)



You have all the fundamental skills of a Python programmer. Where you go from here is up to you — web development, data science, automation, games, machine learning — Python is everywhere.






What's Next



You've completed the 8-part beginner series. From here:





  • Web development: Flask or Django frameworks


  • Data science: Pandas, NumPy, Matplotlib


  • Automation: Scripts to automate tasks


  • Games: Pygame library


  • Machine learning: Scikit-learn, TensorFlow


  • Advanced Python: Decorators, metaclasses, async/await



The fundamentals you've learned here apply to everything. Pick a project that excites you and build it.

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
2 Quellen
Could A.I. Really Kill All Humans?
1 Quelle
The Next Terrorist Attack Is Predictable
1 Quelle
Anthropic Says It Blocked Possible Efforts to Build Biological Weapons
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Python for Beginners — Part 8: Object-Oriented Python

Thematisch verwandte Begriffe: Python, Beginners, Part, ObjectOriented · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...