Master Python OOP: From Classes to Real‑World Objects
This article explains the fundamentals of object‑oriented programming in Python, covering concepts such as encapsulation, inheritance, polymorphism, class definition, instance creation, special methods, garbage collection, and the differences between equality and identity, all illustrated with clear code examples and diagrams.
Object‑Oriented Basics
Python was designed as an object‑oriented language. The core ideas of OOP are often summarized as encapsulation, inheritance, and polymorphism, although the concept itself is more abstract.
What Is Object‑Oriented Programming?
Object‑Oriented Programming (OOP) abstracts a real‑world entity into its attributes and behaviors, then analyzes, designs, and implements a complete program based on that abstraction.
OOP Process Flow
Object‑Oriented Analysis (OOA)
Object‑Oriented Design (OOD)
Object‑Oriented Programming (OOP)
Object‑Oriented Testing (OOT)
Object‑Oriented Maintenance (OOSM)
Defining a Class in Python
A class is a custom data type whose attributes can be of any type.
class <ClassName>(BaseClasses):
class variables...
def __init__(self, ...):
# initializer
def method(self):
# instance method
@staticmethod
def static_method():
pass
@classmethod
def class_method(cls):
pass
def __del__(self):
# destructorExample: collecting phone information.
class Phone:
def __init__(self, name, screen_size, color, ram, rom, camera, battery, price, use):
self.name = name
self.screen_size = screen_size
self.color = color
self.ram = ram
self.rom = rom
self.camera = camera
self.battery = battery
self.price = price
self.use = use
def do(self):
print('经常使用手机' + self.use)
xxx_phone = Phone('iphone11', '6.1英寸', '黑色', '3GB', '128GB', '1200万', '3200mAh', 5499, '打游戏')
print('品牌:{}, 屏幕大小:{}, 颜色:{}, 运行内存:{}, 机身存储:{}, 像素:{}, 电池容量:{}, 价格:{}'.format(
xxx_phone.name, xxx_phone.screen_size, xxx_phone.color, xxx_phone.ram, xxx_phone.rom,
xxx_phone.camera, xxx_phone.battery, xxx_phone.price))
xxx_phone.do()Output:
品牌:iphone11,屏幕大小:6.1英寸,颜色:黑色,运行内存:3GB,机身存储:128GB,像素:1200万,电池容量:3200mAh,价格:5499
经常使用手机打游戏Important Class Conventions
Class names should start with a capital letter.
Always define an __init__ method.
The first parameter of instance methods is conventionally named self.
Object Construction Process
The steps are: allocate memory with __new__, initialize with __init__, then return the object reference.
class Phone:
def __new__(cls, *args, **kwargs):
print('我先执行,开辟内存空间')
return object.__new__(cls)
def __init__(self, name):
self.name = name
print('实例化对象')
def __del__(self):
print('对象被销毁前执行我')
phone1 = Phone('iphone 11')
phone2 = Phone('iphone x')
print(phone1.name)
print(phone2.name)Result shows the order of __new__ and __init__ calls and the destructor execution when objects are garbage‑collected.
Garbage Collection
Python uses a garbage collector that automatically calls an object's destructor before reclaiming memory. Common strategies include reference counting, mark‑and‑sweep, and generational collection.
Equality vs. Identity
Operator == compares values, while is compares object identities (memory addresses).
phone1 = Phone('iphone 11')
phone2 = Phone('iphone 11')
print(phone1.name == phone2.name) # True
print(phone1 == phone2) # False (different objects)
print(phone1 is phone2) # FalseTo make two objects compare equal by ==, override __eq__:
class Phone:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
phone1 = Phone('iphone 11')
phone2 = Phone('iphone 11')
print(phone1 == phone2) # TrueClass Attributes
Attributes defined directly in the class body are shared by all instances.
class Phone:
owner = 'me'
def __init__(self, name):
self.name = name
phone1 = Phone('华为')
phone2 = Phone('荣耀')
print(Phone.owner)
print('这部' + phone1.name + '手机属于:' + phone1.owner)
print('这部' + phone2.name + '手机属于:' + phone2.owner)OOP vs. Procedural Programming
Procedural programming follows a linear sequence of steps, while OOP first models the problem domain with classes and then creates many objects from those templates, making it suitable for larger, more complex projects.
Conclusion
The article introduced the philosophy of object‑oriented programming, basic class definitions, member and class attributes, and demonstrated how Python implements these concepts, providing a foundation for anyone learning Python.
Signed-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.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
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.
