二十四. 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. q次询问,每次给一个x,问1到x的因数个数的和。

    q次询问,每次给一个x,问1到x的因数个数的和. #include<cmath> #include<cstdio> #include<cstring> usingn ...

  2. IDEA中文出现乱码解决(转)

    转自:http://lcl088005.iteye.com/blog/2284696 我是个idea的忠实用户,新公司的项目都是用eclipse做的,通过svn拉下代码后发现,注释的内容里,中文内容都 ...

  3. MongoExport后的负载均衡问题查询及解决:can't accept new chunks because there are still 2 deletes from previous migration

    问题 前一阵有一个数据导出需求,按照各种数据库的使用方法,使用MongoExport方法导出数据,将数据导出到本地文件系统,在导出之后遇到此问题. 此问题和mongoexport的原理有关,我们知道数 ...

  4. 使用sp_addlinkedserver、sp_dropserver 、sp_addlinkedsrvlogin和sp_droplinkedsrvlogin 远程查询数据

    一.sp_addlinkedserver  创建链接服务器. 链接服务器让用户可以对 OLE DB 数据源进行分布式异类查询. 在使用 sp_addlinkedserver 创建链接服务器后,可对该服 ...

  5. Java 文件重命名

    Java 文件重命名 /** * 重命名文件 * @param fileName * @return */ public static void renameFile(String filePath, ...

  6. mysql 主键外键

    外键MUL:一个特殊的索引,用于关键2个表,只能是指定内容 主键PRI:唯一的一个不重复的字段.   # 创建一个表用来引用外键 create table class( -> id int no ...

  7. 谷歌技术"三宝"之BigTable

    转自:https://blog.csdn.net/OpenNaive/article/details/7532589 2006年的OSDI有两篇google的论文,分别是BigTable和Chubby ...

  8. Pandas之分组

    假如我们现在有这样一组数据:星巴克在全球的咖啡店信息,如下图所示.数据来源:starbucks_store_locations.我们想要统计中国每个城市的星巴克商店的数量,那我们应该怎么做呢? 在pa ...

  9. Bumped!【最短路】(神坑

    问题 B: Bumped! 时间限制: 1 Sec  内存限制: 128 MB 提交: 351  解决: 44 [提交] [状态] [命题人:admin] 题目描述 Peter returned fr ...

  10. UVA1401 Remember the Word

    思路 用trie树优化dp 设f[i]表示到第i个的方案数,则有\(f[i]=\sum_{x}f[i+len[x]]\)(x是s[i,n]的一个前缀),所以需要快速找出所有前缀,用Trie树即可 代码 ...