二十四. Python基础(24)--封装
二十四. Python基础(24)--封装
● 知识结构
|
|
|
|
● 类属性和__slots__属性
|
class Student(object): grade = 3 # 也可以写在__slots__属性下面__slots__下面
def __init__(self, name, age, hobby): self.name=name self.age=age # self.hobby=hobby # 如果定义了这个对象属性, 会抛出异常: AttributeError: 'Student' object has no attribute 'hobby'
a=Student('Arroz', 22,'swimming') b=Student('Paul', 30,'skating') print(Student.grade) # 3 print(a.grade) # 3, 类和对象都可以访问静态属性/类属性 a.grade = 5 # 此时没有定义__slos__属性, 类属性grade可写 print(a.grade) # 5 print(b.grade) # python的类变量和C++的静态变量不同,并不是由类的所有对象共享。 # 如果是在C++中, 如果某一个对象修改了静态属性, 其它对象的静态属性(实际上是同一个静态属性)也将改变 print(a.__dict__) # {'name': 'Arroz', 'age': 22, 'grade': 5}
class Student(object): grade = 3 # 也可以写在__slots__属性下面__slots__下面 __slots__ = ['name', 'age'] # 限定可以定义的对象属性为name, age
def __init__(self, name, age, hobby): self.name=name self.age=age # self.hobby=hobby # 如果定义了这个对象属性, 会抛出异常: AttributeError: 'Student' object has no attribute 'hobby'
a=Student('Arroz', 22,'swimming') b=Student('Paul', 30,'skating') print(Student.grade) print(a.grade) # 类和对象都可以访问静态属性/类属性 #a.grade = 5 # 此时定义了__slos__属性, 类属性grade只读: # a.grade = 5 # 此时没有定义__slos__属性, 类属性grade可写 print(a.grade) print(b.grade) # print(a.__dict__) # 'Student' object has no attribute '__dict__' print(dir(a)) # 如果在一个类中添加了__slots__属性,那么这个类的实例将不会拥有__dict__属性 # 但是dir()仍然可以找到并列出它的实例所有有效属性。 |
● 类的特性
|
class Shop: discount = 0.5 # 打五折
def __init__(self,name, price): self.name = name self.__price = price
@property # The @property decorator marks the getter method of a property (@property装饰器标志了一个特性的getter方法) def price(self): return self.__price * Shop.discount
@price.setter def price(self, new_price): self.__price = new_price
@price.deleter def price(self): del self.__price
apple = Shop('apple', 5) # print(apple.__price) # AttributeError: 'Shop' object has no attribute '__price' print('discount:', Shop.discount) #discount: 0.5 print('discount:', apple.discount) #discount: 0.5 print('__price:', apple._Shop__price) # __price: 5 print(apple.price) # 3.75 (调用getter方法) apple.price = 6 # (因为有等号, 所有调用setter方法) print(apple.price) # 4.5 print(apple.__dict__) # {'name': 'apple', '_Shop__price': 6} del apple.price # 调用deleter方法 print(apple.__dict__) # {'name': 'apple'} |
|
# 有关删除属性 class A: pass
a = A() a.name = 'Arroz' print(a.name) # Arroz del a.name # 删除属性 # print(a.name) # AttributeError: 'A' object has no attribute 'name' |
● 什么时候用静态方法
|
class Parent: def __method1(self): print('Foo')
class Son(Parent): def __method2(self): print('Son')
def fun(self): return self.__method2() # return关键字可以省略, 返回值, 即__method2()时中间结果
son = Son() son.fun() # Son
# 什么时候用私有方法? #1.有一些方法的返回值只是用来作为中间结果 #2.父类的方法不希望子类继承 |
● 静态方法 & 类方法
|
class Foo: val1=5 def __init__(self, value): self.val2 = value
@staticmethod def staticfunc(): Foo.val1 = 10 # 可以访问类属性 # 无法访问对象属性
@classmethod def classfunc(cls): cls.val1 = 15 # 可以访问类属性 # 无法访问对象属性
Foo.staticfunc() print(Foo.val1) #10 Foo.classfunc() print(Foo.val1) #15 |
|
静态方法 ① 静态方法是通过类名来操作类属性的, 这是写死在程序中, 而类方法是通过类型参数来操作类属性的 ② 如果子类继承了使用静态方法的类,那么子类继承的静态方法还是在操作父类, 子类需要重写静态方法才能操作子类(也就是需要重写成用子类名来操作类属性) ③ 类方法如果被继承, 那么类型参数会传入子类本身, 也因此, 子类不需要重写类方法(因为cls指本类) |
● 命名元祖
|
#命名元祖: 没有方法、 from collections import namedtuple Point = namedtuple('point',['x','y']) t1 = Point(1,2) print(t1.x, t1.y) # t1.x=3 # AttributeError: can't set attribute |
二十四. Python基础(24)--封装的更多相关文章
- 十四. Python基础(14)--递归
十四. Python基础(14)--递归 1 ● 递归(recursion) 概念: recursive functions-functions that call themselves either ...
- 二十六. Python基础(26)--类的内置特殊属性和方法
二十六. Python基础(26)--类的内置特殊属性和方法 ● 知识框架 ● 类的内置方法/魔法方法案例1: 单例设计模式 # 类的魔法方法 # 案例1: 单例设计模式 class Teacher: ...
- 二十五. Python基础(25)--模块和包
二十五. Python基础(25)--模块和包 ● 知识框架 ● 模块的属性__name__ # my_module.py def fun1(): print("Hello& ...
- python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法
python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法window安装redis,下载Redis的压缩包https://git ...
- python学习笔记(二十四)继承与封装
继承(extends)就是把多个类中相同的成员给提取出来定义到一个独立的类中,然后让这多个类和该独立的类产生一个关系,这多个类就具备了这些类容,这个关系就叫做继承. 实现继承的类称为子类,也叫派生类, ...
- 二十四 Python分布式爬虫打造搜索引擎Scrapy精讲—爬虫和反爬的对抗过程以及策略—scrapy架构源码分析图
1.基本概念 2.反爬虫的目的 3.爬虫和反爬的对抗过程以及策略 scrapy架构源码分析图
- python3.4学习笔记(二十五) Python 调用mysql redis实例代码
python3.4学习笔记(二十五) Python 调用mysql redis实例代码 #coding: utf-8 __author__ = 'zdz8207' #python2.7 import ...
- Bootstrap<基础二十四> 缩略图
Bootstrap 缩略图.大多数站点都需要在网格中布局图像.视频.文本等.Bootstrap 通过缩略图为此提供了一种简便的方式.使用 Bootstrap 创建缩略图的步骤如下: 在图像周围添加带有 ...
- 使用Typescript重构axios(二十四)——防御XSRF攻击
0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...
随机推荐
- Spark生态以及原理
spark 生态及运行原理 Spark 特点 运行速度快 => Spark拥有DAG执行引擎,支持在内存中对数据进行迭代计算.官方提供的数据表明,如果数据由磁盘读取,速度是Hadoop MapR ...
- javaScript函数立即执行《1》
javaScript函数立即执行<1> 函数立即执行,常见两种写法: >>> (function(){ })() >>> (function(){ }( ...
- 富文本之BootStrap-wysiwyg 带图片上传功能
BootStrap-wysiwyg插件具有良好的编辑功能和展示效果. 一.使用方法在网上有很多,在此记录自己使用过程中的一些问题和解决方式. 相关依赖: bootstrap-wysiwyg.js (核 ...
- java Timer 定时每天凌晨0点执行任务
import java.util.TimerTask; /** * 执行内容 * @author admin_Hzw * */ public class Task extends TimerTask ...
- NOIP2012借教室
题目描述 Description 在大学期间,经常需要租借教室.大到院系举办活动,小到学习小组自习讨论,都需要 向学校申请借教室.教室的大小功能不同,借教室人的身份不同,借教室的手续也不一样. 面对海 ...
- 第十节 JS运动中级
链式运动框架. 回调函数 运动停止时,执行函数 运动停止时,开始下一次运动 <!DOCTYPE html> <html lang="en"> <hea ...
- nginx与PHP配置
一.安装依赖包 yum -y install libxml2 libxml2-devel openssl openssl-devel curl curl-devel libjpeg li ...
- 生成id
package com.develop.web.util; import java.security.MessageDigest; import java.text.SimpleDateFormat; ...
- jQuery 自执行函数
jQuery 自执行函数 // 为了避免三方名冲突可将全局变量封装在自执行函数内 (function (arg) { var status = 1; arg.extend({ 'xsk': funct ...
- ARM基础
ARM汇编:(APCS过程调用标准) 汇编:用助记符(如$ # .)代替操作码,用地址符号或标签代替地址码的编程语言 特点: 优点:可以直接访问硬件,目标代码简短,执行速度快(CPU启动时需要直接操作 ...

