下面是Python面向对象之类的封装操作示例的完整攻略:
什么是封装
在面向对象编程中,封装是一种将数据和方法包装在一起的机制。实现封装的方法是使用类来定义一个对象,类包含了数据和方法,而对象则是类的实例。通过封装,对象的数据和方法只能通过公共接口进行访问,而不可以从外部直接访问。
如何实现封装
1. 使用“_”来实现私有化
在Python中,我们可以使用“_”来表示类中的某个属性为私有属性,或者说是受保护的属性,这样就可以将属性隐藏起来,不让外部代码直接对其进行访问。以下是一个简单的例子:
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def display(self):
print(f"My name is {self._name}, and I'm {self._age} years old.")
p = Person("Tom", 38)
p.display()
# 输出 My name is Tom, and I'm 38 years old.
print(p._age) # 直接访问私有属性
# 报错 AttributeError: 'Person' object has no attribute '_age'
当我们使用“_”来实现私有化时,虽然外部代码可以访问私有属性,但不建议这样做,因为这样会破坏封装的原则。
2. 使用@property来实现Getter和Setter方法
除了使用“_”来实现私有化之外,还可以使用@property来实现Getter和Setter方法。Getter方法用来获取对象的属性值,Setter方法用来设置对象的属性值。以下是一个例子:
class Rectangle:
def __init__(self, length, width):
self._length = length
self._width = width
@property
def length(self):
return self._length
@length.setter
def length(self, value):
self._length = value
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
def area(self):
return self._length * self._width
r = Rectangle(10, 5)
print(f"Length = {r.length}, Width = {r.width}, Area = {r.area()}")
r.length = 15
r.width = 10
print(f"Length = {r.length}, Width = {r.width}, Area = {r.area()}")
通过使用@property来实现Getter和Setter方法,我们既可以控制对象的属性访问,又可以保证代码的简洁性。
示例说明
示例一:账号类
以下是一个账号类的实现,通过使用“_”来实现私有化和使用@property来实现Getter和Setter方法,来实现对账号类的封装:
class Account:
def __init__(self, account_id, balance):
self._id = account_id
self._balance = balance
@property
def id(self):
return self._id
@property
def balance(self):
return self._balance
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if amount > self._balance:
raise ValueError("Not enough balance.")
self._balance -= amount
a = Account("111111", 1000.0)
print(f"AccountId = {a.id}, Balance = {a.balance}")
a.deposit(500.0)
print(f"AccountId = {a.id}, Balance = {a.balance}")
a.withdraw(300.0)
print(f"AccountId = {a.id}, Balance = {a.balance}")
示例二:考试类
以下是一个考试类的实现,每次考试的分数只能在0到100分之间,我们通过使用@property来实现Getter和Setter方法来实现对考试类的封装:
class Exam:
def __init__(self, name, score):
self._name = name
self._score = 0
self.score = score
@property
def name(self):
return self._name
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if value < 0 or value > 100:
raise ValueError("Score must be between 0 and 100.")
self._score = value
e = Exam("Math", 80)
print(f"ExamName = {e.name}, Score = {e.score}")
e.score = 90
print(f"ExamName = {e.name}, Score = {e.score}")
e.score = 110
# 报错 ValueError: Score must be between 0 and 100.
通过使用@property来实现Getter和Setter方法,我们在封装数据的同时,对数据进行了控制,从而保证了代码的稳定性和安全性。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python面向对象之类的封装操作示例 - Python技术站