Python3 面向对象进阶
发布时间:2020-12-20 10:20:45 所属栏目:Python 来源:网络整理
导读:目录 组合 概念 目的 实现方式 封装 概念 目的 实现方式 访问限制 概念 目的 实现方式 Property 概念 目的 实现方式 多态 概念 目的 抽象类 概念 目的 实现方法 鸭子类型 组合 概念 组合指的是一个对象中的属性是另一个对象 目的 组合的目的和继承一样,为了
目录
组合概念
目的
实现方式# 1 class Other: def func(self): print('from other') class Foo: def __init__(self): self.other = other() def func(self): self.other.func() foo = Foo() foo.func() # from other # 2 class Other: def func(self): print('from other') class Foo: pass foo = Foo() other_obj = Other() foo.func = other_obj.func foo.func() # from other
封装概念
目的
实现方式
访问限制概念
目的
class Foo: __name = 'bigb' def __func(self): print('secret') foo = Foo() print(foo._Foo__name) # bigb foo._Foo__func() # secret 实现方式# 1 class PyMan: language = 'Python' def __init__(self,name,age,gender): self.__name = name self.__age = age self.__gender = gender # 打印用户信息接口 def get_info(self): username = input('请输入用户名: ') password = input('请输入密码: ') if username == 'bigb' and password == '123': print(f''' 姓名: {self.__name} 年龄: {self.__age} 性别: {self.__gender} ''') # 修改用户信息接口 def set_info(self,gender): if not isinstance(name,str): raise TypeError if not isinstance(age,int): raise TypeError if not isinstance(gender,str): raise TypeError self.__name = name self.__age = age self.__gender = gender bigb = PyMan('bigb',18,'male') bigb.get_info() bigb.set_info() # 2 class ATM: def __insert_card(self): print('插卡') def __input_pwd(self): print('输入密码') def __input_money(self): print('输入金额') def __get_monet(self): print('执行吐钱') def __print_bill(self): print('打印账单') def withdraw(self): self.__insert_card() self.__input_pwd() self.__input_money() self.__get_monet() self.__print_bill() print('取款程序执行完毕!') atm = ATM() atm.withdraw() ''' 插卡 输入密码 输入金额 执行吐钱 打印账单 取款程序执行完毕! ''' Property概念
目的
实现方式
class People: def __init__(self,weight,height): self.name = name self.weight = weight self.height = height @property def bmi(self): return self.weight / (self.height * self.height) bigb = People('bigb',70,1.8) # 如果不用@property,则print(bigb.bmi()) print(bigb.bmi) 多态概念
目的
抽象类概念
目的
实现方法
import abc class Animal(metaclass=abc.ABCMeta): @abc.abstractmethod def eat(self): pass @abc.abstractmethod def drink(self): pass class Pig(Animal): def eat(self): print('pig is eating...') peppa = Pig()
父类方法被 鸭子类型
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |