Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python Classes: A Beginner's Guide

Tech Apr 23 31
class MyClass:
    # Class attribute: defined outside methods but inside class
    class_attribute = "I am a class attribute"
    
    # Initialization method (constructor)
    def __init__(self, name, age):
        # Instance attributes
        self.name = name
        self.age = age

    def greet(self):
        # Instance method
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

    @classmethod
    def class_method(cls):
        # Class method
        print(f"This is a class method of {cls.__name__}")

    @staticmethod
    def static_method():
        # Static method
        print("This is a static method")

    def __str__(self):
        # Special method: string representation
        return f"MyClass({self.name}, {self.age})"

# Create an instance (object) of MyClass
my_instance = MyClass("Alice", 30)

# Access class attribute
print(MyClass.class_attribute)

# Call instance method
my_instance.greet()

# Access instance attributes
print(my_instance.name)
print(my_instance.age)

# Call class method
MyClass.class_method()

# Call static method
MyClass.static_method()

# Use special method
print(my_instance)

String Formatting Note When you write:

print("Hello, my name is self.name and I am self.age years old")

The output is literal: Hello, my name is self.name and I am self.age years old.

To output the values of self.name and self.age, you must use string formatting. For example, use an f-string (Python 3.6+):

print(f"Hello, my name is {self.name} and I am {self.age} years old")

Or use the .format() method:

print("Hello, my name is {} and I am {} years old".format(self.name, self.age))
Tags: Python

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.