二十四. 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)--封装的更多相关文章

  1. 十四. Python基础(14)--递归

    十四. Python基础(14)--递归 1 ● 递归(recursion) 概念: recursive functions-functions that call themselves either ...

  2. 二十六. Python基础(26)--类的内置特殊属性和方法

    二十六. Python基础(26)--类的内置特殊属性和方法 ● 知识框架 ● 类的内置方法/魔法方法案例1: 单例设计模式 # 类的魔法方法 # 案例1: 单例设计模式 class Teacher: ...

  3. 二十五. Python基础(25)--模块和包

    二十五. Python基础(25)--模块和包 ● 知识框架   ● 模块的属性__name__ # my_module.py   def fun1():     print("Hello& ...

  4. python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法

    python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法window安装redis,下载Redis的压缩包https://git ...

  5. python学习笔记(二十四)继承与封装

    继承(extends)就是把多个类中相同的成员给提取出来定义到一个独立的类中,然后让这多个类和该独立的类产生一个关系,这多个类就具备了这些类容,这个关系就叫做继承. 实现继承的类称为子类,也叫派生类, ...

  6. 二十四 Python分布式爬虫打造搜索引擎Scrapy精讲—爬虫和反爬的对抗过程以及策略—scrapy架构源码分析图

    1.基本概念 2.反爬虫的目的 3.爬虫和反爬的对抗过程以及策略 scrapy架构源码分析图

  7. python3.4学习笔记(二十五) Python 调用mysql redis实例代码

    python3.4学习笔记(二十五) Python 调用mysql redis实例代码 #coding: utf-8 __author__ = 'zdz8207' #python2.7 import ...

  8. Bootstrap<基础二十四> 缩略图

    Bootstrap 缩略图.大多数站点都需要在网格中布局图像.视频.文本等.Bootstrap 通过缩略图为此提供了一种简便的方式.使用 Bootstrap 创建缩略图的步骤如下: 在图像周围添加带有 ...

  9. 使用Typescript重构axios(二十四)——防御XSRF攻击

    0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...

随机推荐

  1. Javascript根据id获取数组对象

    在业务中,列表页跳转详情页时,经常会将Id值传入,然后再根据id值异步获取数据. 假设有服务端的json数据:  <注意,这里的data是指已经从后端获取的json, 而非后端原始的文件> ...

  2. vue使用桌面Element-UI和移动端MintUI的UI框架

    vue使用桌面Element-UI和移动端MintUI的UI框架 element-uiElement - 网站快速成型工具http://element-cn.eleme.io/#/zh-CN 安装:n ...

  3. 连接redis错误:ERR Client sent AUTH, but no password is set

    问题原因:没有设置redis的密码 解决:命令行进入Redis的文件夹: D:\Redis-x64-3.2.100>redis-cli.exe 查看是否设置了密码: 127.0.0.1:6379 ...

  4. 盒子布局、标签特性display、浮动、定位position

    盒子模型布局: 盒子模型:每个标签都是一个盒子 盒子在页面显示在大小是:自身宽度+边框+边距(内边框+外边距) 如果一个盒子设置了边框,则边框需要被加两遍.若果设置了边距则内外边距根据设置情况要被加两 ...

  5. LNMP 如何安装mongodb

    wget -c http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.6.4.tgztar -zxvf mongodb-linux-x86_64 ...

  6. Docker 部署 elk + filebeat

    Docker 部署 elk + filebeat kibana 开源的分析与可视化平台logstash 日志收集工具 logstash-forwarder(原名lubmberjack)elastics ...

  7. opencv学习之路(31)、GrabCut & FloodFill图像分割

    一.GrabCut 1.利用Rect做分割 #include "opencv2/opencv.hpp" using namespace cv; void main() { Mat ...

  8. kubernetes endpoint一会消失一会出现的问题剖析

    问题现象 发现某个service的后端endpoint一会显示有后端,一会显示没有.显示没有后端,意味着后端的address被判定为notready. endpoint不正常的时候: [root@lo ...

  9. 字段值为 null 时,序列化或反序列化成其他值

    using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.G ...

  10. js中实现截取数组的后几个元素作为一个新数组的方法

    有时候我们会遇到这种需求,截取数组中后5个元素作为一个新数组,且顺序不能变.数组中的slice()方法和splice()方法都可以实现这样的操作. const arr = [1,2,7,2,6,0,3 ...