封装、property装饰器

封装分为3种情况:封装对象的属性、封装类的属性、封装方法。

封装对象的属性:(在属性名前加双下划线__)

class Person:
def __init__(self,height,weight,name,sex):
self.__height = height #私有对象属性:不在外面调它
self.__weight = weight
self.__name = name
self.__sex = sex def bmi(self):
return self.__weight / self.__height ** 2 def tell_height(self):
print(self.__height) def tell_weight(self):
return self.__weight def set_weight(self,new_weight):
if new_weight > 20:
self.__weight = new_weight egg = Person(1.7,125,'egon',None)
egg.tell_height()#在类内调
print(egg.__dict__)#查看类内的私有属性
print(egg._Person__height)#在类外调用

通过私有属性后,我们可以更好的确保属性数值不会随意修改。

封装属性我们可以在set——weight里约束属性值得更改

class Person:
def __init__(self,height,weight,name,sex):
self.__height = height #私有对象属性:不在外面调它
self.__weight = weight
self.__name = name
self.__sex = sex def bmi(self):
return self.__weight / self.__height ** 2 def tell_height(self):
print(self.__height) def tell_weight(self):
return self.__weight def set_weight(self,new_weight):
if new_weight > 20:
self.__weight = new_weight egg = Person(1.7,125,'egon',None)
egg.tell_height()#在类内调
# print(egg.__dict__)#查看类内的私有属性
print(egg._Person__height)#在类外调用
egg.set_weight(105)
print(egg.tell_weight()) #私有属性:
# 在本类内就可以正常调用
# 在本类外就必须_类名__属性名调用,(不建议你调)

封装类的属性

class Goods:
__discount = 0.8 #类的私有属性
def __init__(self,name,price):
self.name = name
self.price = price
def goods_price(self):
return self.price * Goods.__discount banana = Goods('banana',2)
print(banana.goods_price())#类内调用
# print(Goods.__dict__)#查看类的私有属性
print(Goods._Goods__discount)#在类外调用私有属性

封装对象的方法

class Foo:
def __init__(self,height,weight):
self.height = height
self.weight = weight def tell_bmi(self):
#体重/身高的平方
return self.weight / self.__heightpow() def __heightpow(self): #私有方法
return self.height * self.height egon = Foo(1.7,125)
print(egon.tell_bmi())
print(Foo.__dict__)
print(egon._Foo__heightpow()) #类外调用方法 #私有的:类属性 对象属性 方法
#变成私有的 :__名字
#在类内都是照常使用
#在类外部就变形称为:_类名__名字 #定义私有~的原因
#不让外部的人瞎调,不让子类继承

封装的进阶

通过property装饰器把一个方法变成一个属性用

from math import pi
class Circle:
def __init__(self,radius):
self.radius = radius @property #area = property(area)
def area(self):
return pi*self.radius*self.radius @property
def perimeter(self):
return 2*pi*self.radius
c = Circle(10)
print(c.area)
print(c.perimeter)
我们调用area方法和perimeter方法就像调用属性一样

上个牛逼的代码(缓存网页的,用面向对象的方法)

from urllib.request import urlopen
class Web_page:
def __init__(self,url):
self.url = url
self.__content = None#私有对象属性 @property
def content(self): #content 内容,相当于一个属性
if self.__content: #做了一个什么转换 _Web_page__content
return self.__content
else:
self.__content = urlopen(self.url).read().decode(encoding='utf-8') #做缓存
return self.__content mypage = Web_page('http://www.baidu.com')
print(mypage.content)
print(mypage.content)

计算传入数据的值

#计算传入的数据的值
class Num:
def __init__(self,*args):
print(args)
if len(args) == 1 and (type(args[0]) is list or type(args[0]) is tuple):
self.members = args[0]
else:
self.members = args @property
def sum(self):
return sum(self.members) @property
def average(self):
return self.sum/len(self.members) @property
def min(self):
return min(self.members) @property
def max(self):
return max(self.members)
nums = Num([1,2,3])
print(nums.sum)
# print(nums.average)
# print(nums.min)
# print(nums.max)
# num2 = Num(4,5,6)
# print(num2.sum)
# print(num2.average)
# print(num2.min)
# print(num2.max)

property装饰器(property、set、del方法)

class Goods:
__discount = 0.8 #类的私有属性
def __init__(self,name,price):
self.name = name
self.__price = price
@property
def price(self):
new_price=self.__price * Goods.__discount
return new_price
@price.setter
def price(self,new_price):
if type(new_price) is int:
self.__price = new_price
@price.deleter
def price(self):
del self.__price apple = Goods('apple',10)
print(apple.price)
apple.price = 20
print(apple.price)

总结

#@property把一个类中的方法 伪装成属性
#obj.func()
#obj.func -->属性
#因为属性不能被修改
#@funcname.setter,来修改
#obj.func = new_value 调用的是被@funcname.setter装饰器装饰的方法 #被@property装饰的方法名必须和被@funcname.setter装饰的方法同名 #@funcname.deleter
#在执行del obj.func 的时候会调用被这个装饰器装饰的方法(同名)

 

python之面向对象进阶2的更多相关文章

  1. python基础——面向对象进阶下

    python基础--面向对象进阶下 1 __setitem__,__getitem,__delitem__ 把对象操作属性模拟成字典的格式 想对比__getattr__(), __setattr__( ...

  2. python基础——面向对象进阶

    python基础--面向对象进阶 1.isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 ...

  3. Python 3 面向对象进阶

    Python 3 面向对象进阶 一.    isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的 ...

  4. day021|python之面向对象进阶1

    面向对象进阶 目录 面向对象进阶 1 继承 1.1 继承入门 1.1.1 继承基础 1.1.2 类的基本使用 1.2 多继承 1.2.1 多继承的基本使用 1.2.2 多继承以后的重复性 1.3 类的 ...

  5. python基础-面向对象进阶

    一.什么是反射 反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问.检测和修改它本身状态或行为的一种能力(自省).这一概念的提出很快引发了计算机科学领域关于应用反射性的研究.它首先被 ...

  6. python学习------面向对象进阶

    一 isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 class Foo(object) ...

  7. python开发面向对象进阶:反射&内置函数

    isinstance和issubclass isinstance(obj,cls)检查是否obj是否是类 cls 的对象或者子类的对象 class Foo(object): pass class ba ...

  8. Python之面向对象进阶------反射(Day26)

    一 classmethod class Classmethod_Demo(): role = 'dog' @classmethod def func(cls): print(cls.role) Cla ...

  9. python之面向对象进阶3

    1.isinstace和issubclass 2.staticmethod和classmethod 3.反射(hasattr.getattr.setattr.delattr等四个方法) 4.内置方法 ...

随机推荐

  1. vue router history模式开发ngnix配置

    一.前沿 现在很多用vue-router开发页面的时候,都习惯使用hash路由莫模式,如:https://xxxx/#/index/share?code=dsfsd.这种模式在做pc端开发时候挺好用的 ...

  2. freemarker中使用<@spring.*>标签实现国际化

    freemarker实现国际化使用自定义指令<@spring>实现,通过@符号可以看出是自定义的指令,在哪里定义的呢? 路径如下:org/springframework/spring-we ...

  3. shell | {}和()

    执行 bash -n xx.sh用于检测脚本语法是否有错误 bash -x xx.sh用于追踪执行 ${var} 用于限定变量名称的范围,并且支持通配符 $(cmd) shell会先执行括号的cmd, ...

  4. [android] 安卓消息推送的几种实现方式

    消息推送的目的:让服务器端及时的通知客户端 实现方案 轮询:客户端每隔一定的时间向服务器端发起请求,获得最新的消息 特点:如果用在最新新闻通知上,效率就有点低了,技术简单,好实现 应用场景:服务器端以 ...

  5. 数据机构-折半查找法(二分查找法)-Python实现

    Python实现二分查找法(基于顺序表) class List: elem=[] #存储顺序表元素 last=-1 #设置初始为-1 SeqList = List() #创建一个顺序表 print(& ...

  6. webpack4 系列教程(二): 编译 ES6

    今天介绍webpack怎么编译ES6的各种函数和语法.敲黑板:这是webpack4版本哦, 有一些不同于webpack3的地方. >>> 本节课源码 >>> 所有课 ...

  7. 通过Eureka自带REST API强行剔除失效服务

    1.确定需要强行剔除的服务 2.执行接口 方便复制: http://{ip}:{port}/eureka/apps/CONFIG-SERVER-TEST/tom:config-server-test: ...

  8. SQL Server中的数据类型

    参考 SQL Server 2012编程入门经典(第4版) SQL Server 自带的数据类型 整型: 货币 近似小数 日期/时间 特殊数字 字符 Unicode 二进制 其他

  9. 自定义SharePoint2013 master page

    SharePoint uses templates to define and render the pages that a site displays. The structure of a Sh ...

  10. JS之this应用详解

    目录 1. this作为全局变量2. 作为对象方法的调用3. 作为构造函数调用4. apply调用 this是Javascript语言的一个关键字.它代表函数运行时,自动生成的一个内部对象,只能在函数 ...