python之面向对象进阶2
封装、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的更多相关文章
- python基础——面向对象进阶下
python基础--面向对象进阶下 1 __setitem__,__getitem,__delitem__ 把对象操作属性模拟成字典的格式 想对比__getattr__(), __setattr__( ...
- python基础——面向对象进阶
python基础--面向对象进阶 1.isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 ...
- Python 3 面向对象进阶
Python 3 面向对象进阶 一. isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的 ...
- day021|python之面向对象进阶1
面向对象进阶 目录 面向对象进阶 1 继承 1.1 继承入门 1.1.1 继承基础 1.1.2 类的基本使用 1.2 多继承 1.2.1 多继承的基本使用 1.2.2 多继承以后的重复性 1.3 类的 ...
- python基础-面向对象进阶
一.什么是反射 反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问.检测和修改它本身状态或行为的一种能力(自省).这一概念的提出很快引发了计算机科学领域关于应用反射性的研究.它首先被 ...
- python学习------面向对象进阶
一 isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 class Foo(object) ...
- python开发面向对象进阶:反射&内置函数
isinstance和issubclass isinstance(obj,cls)检查是否obj是否是类 cls 的对象或者子类的对象 class Foo(object): pass class ba ...
- Python之面向对象进阶------反射(Day26)
一 classmethod class Classmethod_Demo(): role = 'dog' @classmethod def func(cls): print(cls.role) Cla ...
- python之面向对象进阶3
1.isinstace和issubclass 2.staticmethod和classmethod 3.反射(hasattr.getattr.setattr.delattr等四个方法) 4.内置方法 ...
随机推荐
- 一、Windows下Git的安装与配置
一.下载Git安装包 1.打开Git的官方网站:https://git-scm.com/ 2.找到下载页:https://git-scm.com/downloads 3.找到Windows版本下载页面 ...
- Linux 服务器命令,持续更新……
记录一下常用命令给自己备忘备查,会持续更新-- 一.查看和修改Linux的时间 1. 查看时间和日期,命令: date 2.设定时间和日期 例如:将系统日期修改成2020年2月14日12点的命令: d ...
- kubernetes系列(一)安装和配置
谈到kubernetes(或者说k8s)不得不提到云计算.虚拟化以及容器技术,相关介绍网上一大堆,不再赘述.而kubernetes的出现就是为了高效的管理云端运行的docker容器. 环境 docke ...
- Java 使用 happen-before 规则实现共享变量的同步操作
前言 熟悉 Java 并发编程的都知道,JMM(Java 内存模型) 中的 happen-before(简称 hb)规则,该规则定义了 Java 多线程操作的有序性和可见性,防止了编译器重排序对程序结 ...
- Tests of the Equality of Two Means
Introduction In this lesson, we'll continue our investigation of hypothesis testing. In this case, w ...
- Runtime和Process
private void runByshcommand(String command) { try { System.out.println("开始执行命令....."); Pro ...
- 【读书笔记】iOS-设置应用的硬件需求
如果你的应用需要一些特定的硬件设备才能运行,你可以在应用的Info.plist文件中添加应用运行所需的硬件列表.如果设备上没有这些硬件的话,你的应用将不会启动. 如图,找到Info.Plist---& ...
- python之黏包和黏包解决方案
黏包现象主要发生在TCP连接, 基于TCP的套接字客户端往服务端上传文件,发送时文件内容是按照一段一段的字节流发送的,在接收方看来,根本不知道该文件的字节流从何处开始,在何处结束. 两种黏包现象: 1 ...
- for each....in、for in、for of
一.一般的遍历数组的方法: var array = [1,2,3,4,5,6,7]; for (var i = 0; i < array.length; i) { console.log(i,a ...
- vue引入bootstrap——webpack
想要在vue中引入bootstrap,引入的时候需要按照如下的步骤进行. 1.引入jquery 2.引入bootstrap 阅读本文前,应该能够搭建环境,使用vue-cli进行项目的创建,可以参考 ...