Master Python OOP: Class Attributes, Methods, Inheritance, super() & @property
This article explains Python's object‑oriented fundamentals, covering class and instance attributes, instance, class and static methods, inheritance techniques, the super() function, and the @property decorator, each illustrated with clear code examples.
1. Basic Use of Object‑Oriented Classes
Key Points
Attributes: class attributes and instance attributes
Methods: instance methods, class methods, static methods
A class can access its class attributes, class methods, and static methods
Code Example
class A(object):
# class attribute
class_a = 20
def __init__(self):
# instance attribute
self.a = 10
# instance method
def a_print(self):
print("a_print")
# class method
@classmethod
def class_print(cls):
print('class_print')
# static method
@staticmethod
def static_print():
print("static_print")
# Access class attribute (cannot access instance attribute directly)
print(A.class_a)
# Access instance attribute via an object
print(A().a)
# Call class method
A.class_print()
# Call static method
A.static_print()
# Two ways to call instance method
A.a_print(A())
A().a_print()2. Class Calls and Attribute Access
Key Points
To invoke another class's methods or attributes within a class, use inheritance or attribute assignment.
Code Example
# Inheritance
class B(A):
def b_print(self):
print("b_print")
B().b_print()
B().a_print()
# Attribute‑assignment style
class C(object):
obj_a = A()
def c_print(self):
print('c_print')
# Call method of A through C's attribute
C.obj_a.a_print()3. Using super() and @property
Key Points
super() calls a method from the parent class.
Typical scenario: override a parent method and extend its behavior.
@property allows a method to be accessed like an attribute, without parentheses.
Code Example
class A(object):
def a_print(self):
print("a_print")
class B(A):
def a_print(self):
# call parent method
super().a_print()
print("add_data")
@property
def data(self):
print("data")
B().a_print()
# Access method as property
B().dataSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
