027-python面向对象-私有方法-封装性

本文介绍了Python中私有方法的使用方式,通过实例展示了如何在类内部定义和调用私有方法,以及如何实现封装以保护类的内部状态。

私有方法和私有变量的封装是类似的,只要在方法前面加上“__”就是私有方法了。

class Animal(object):
    """定义动物类"""

    def __init__(self, age, sex=1, weight=0.0):
        self.age = age
        self.sex = sex
        self.__weight = weight

    def eat(self):
        self.__weight += 0.2
        print(self.__weight)
        print("eat...")
        self.__run()

    def __run(self):
        self.__weight -= 0.1
        print("run...")

a1 = Animal(2, 0, 10.0)
# a1.run()
a1.eat()

私有方法可以在类的内部访问,不能在外部访问,否者会发生错误。
如果一定要在类的外部进行私有方法也是可以的。与私有变量类似,_类名__方法,这样会破坏封装。

### Python 面向对象编程中的封装和继承 #### 封装的概念与用法 封装是一种将数据(属性)和行为(方法)绑定到一起的技术,通过这种方式隐藏内部实现细节并提供对外接口。在 Python 中,可以通过类来定义封装的对象。通常情况下,私有属性和方法会被标记为单下划线 `_` 或双下划线 `__` 开头,表示这些成员不应该被外部直接访问。 以下是封装的一个简单示例: ```python class BankAccount: def __init__(self, owner, balance=0): self.owner = owner self.__balance = balance # 私有属性 def deposit(self, amount): if amount > 0: self.__balance += amount print(f"存款成功,当前余额:{self.__balance}") else: print("存款金额需大于零") def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount print(f"取款成功,当前余额:{self.__balance}") else: print("取款失败,余额不足或输入不合法") def get_balance(self): return f"账户余额:{self.__balance}" account = BankAccount("Alice", 100) print(account.get_balance()) account.deposit(50) account.withdraw(30) # 尝试访问私有属性会报错 # print(account.__balance) ``` 在这个例子中,`__balance` 是一个私有变量,无法从外部直接修改它[^1]。 --- #### 继承的概念与用法 继承允许创建一个新的类(子类),该新类可以从现有的类(父类)那里获取其所有的功能,并可以选择性地覆盖某些方法或者添加新的方法。这有助于提高代码的可重用性和扩展性。 下面是一个关于动物及其声音的例子: ```python class Animal: def __init__(self, name): self.name = name def speak(self): raise NotImplementedError("子类必须实现此方法") class Dog(Animal): def speak(self): return f"{self.name} says Woof!" class Cat(Animal): def speak(self): return f"{self.name} says Meow!" animals = [Dog("Rex"), Cat("Mittens")] for animal in animals: print(animal.speak()) ``` 在此处,`Dog` 和 `Cat` 类都继承自 `Animal` 类,并实现了自己的 `speak()` 方法[^2]。 如果存在多重继承,则需要注意调用顺序以及可能引发的方法冲突问题。例如,在 C3 线性化算法的帮助下解决 MRO(Method Resolution Order)。以下是一段涉及多个基类的情况: ```python class A: def who_am_i(self): print('I am a class A') class B(A): def who_am_i(self): print('I am a class B') class C(A): def who_am_i(self): print('I am a class C') class D(B, C): pass d_instance = D() d_instance.who_am_i() # 输出取决于 MRO 的解析结果 print(D.mro()) # 显示实际查找路径 ``` 这里展示了如何利用超类初始化器完成更复杂的场景设置[^4]。 --- #### 结合封装与继承的实际应用案例 考虑构建一个简单的员工管理系统,其中既有普通职员也有经理角色,他们共享一些共同特征但也具备各自独特之处。 ```python class Employee: def __init__(self, emp_id, name, salary): self._emp_id = emp_id # 受保护字段 self.name = name # 公开字段 self.salary = salary # 公开字段 def display_info(self): return f"ID: {self._emp_id}, Name: {self.name}, Salary: ${self.salary}" class Manager(Employee): def __init__(self, emp_id, name, salary, department): super().__init__(emp_id, name, salary) # 使用super函数调用父级构造器 self.department = department # 新增部门信息 def manage_department(self): return f"{self.name} manages the {self.department} department." manager = Manager(emp_id='MGR_007', name="John Doe", salary=90000, department="Sales") employee = Employee(emp_id='EMP_123', name="Jane Smith", salary=60000) print(manager.display_info()) # 来源于Employee类的功能 print(employee.display_info()) # 同样来源于Employee类的功能 print(manager.manage_department()) # 特定于Manager的行为 ``` 以上程序片段清楚表明了怎样合理运用继承机制减少重复编码量的同时还增强了灵活性[^3]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值