Python Classes: A Beginner's Guide
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))