python面向对象编程

本篇内容:

  •   1、反射
  •   2、面向对象编程
  •   3、面向对象三大特性
  •   4、类成员
  •   5、类成员修饰符
  •   6、类的特殊成员
  •   7、单例模式

反射

python 中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。

import commas 同等于下面字符串导入模块

inp = input("请输入模块名:")
dd
= import(inp)

ret =dd.f1()
print(ret)

通过字符串的形式导入模块
#应用根据用户输入导入模块
inp = input("请输入模块:")
inp_func = input("请输入执行的函数:")

# __import__ 以字符串的形式导入模块
moudle = import(inp)
#getattr 用以去某个模块中寻找某个函数
target_func = getattr(moudle,inp_func)

relust = target_func()
print(relust)

指定函数中执行指定函数
1、getattr
通过字符串的形式去某个模块中寻找东西
import commas

#去 commas,寻找 name 变量,找不到返回 none
target_func = getattr(commas ,"name",None)
print(target_func)

demo
2、hasattr
通过字符串的形式去某个模块中判断东西是否存在
import commas

#去 commas 模块中寻找 f1,有返回 true,没有返回 none
target_func = hasattr(commas,"f1")
print(target_func)

demo
3、setattr
通过字符串的形式去某个模块中设置东西
import commas

#去 commas 模块中寻找 name,有返回 true,没有返回 none
target_func1 = hasattr(commas,"name")
print(target_func1)

#在内存里往 commas 模块中添加 name = "zhangyanlin"
setattr(commas,"name","zhangyanlin")
#在内存里往 commas 模块中创建函数
setattr(commas,"f3",lambda x: "zhen" if x >10 else "jia")

#去 commas 模块中寻找 name,有返回 true,没有返回 none
target_func = hasattr(commas,"name")
print(target_func)

demo
4、delattr
import commas

target_func = hasattr(commas,"f1")
print(target_func)

del_func = delattr(commas,"f1")

target_func = hasattr(commas,"f1")
print(target_func)

demo

  案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'''
基于web框架实现路由功能
'''
 
url = str(input("请输入URL:"))  #输入URL,先输入模块,后面加函数
 
target_moudle,target_func = url.split("/") # 用/把分割开,前面是模块 后面是函数
 
moudle = __import__(target_moudle,fromlist=True#导入模块
 
if hasattr(moudle,target_func):   #判断模块里有这个函数
    target_func = getattr(moudle,target_func)   #找到那个函数
    ret = target_func()   #执行函数
    print(ret)
else:                 #否则报错
    print("404") 

 

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self,name):
    self.name </span>=<span style="color: rgba(0, 0, 0, 1)"> name

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> login(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">登录请按1:</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)

obj = Foo("zhangyanlin")
ret
= getattr(obj,"name")
print(ret)
#反射
#
以字符串的形式去对续航中操作成员
#
反射:类,只能找类的成员
ret = hasattr(Foo,"login")
print(ret)

#反射:对象,既可以找对象也能找类的成员
ret = hasattr(obj,"name")
print(ret)
ret
= hasattr(obj,"login")
print(ret)

反射类实例

面向对象编程

  • 面向过程:根据业务逻辑从上到下写垒代码
  • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
  • 面向对象:对函数进行分类和封装,让开发“更快更好更强...”

面向过程编程最易被初学者接受,其往往用一长段代码来实现指定功能,开发过程中最常见的操作就是粘贴复制,即:将之前实现的代码块复制到现需功能处。

 

1、创建类和对象

面向对象编程是一种编程方式,此编程方式的落地需要使用 “类” 和 “对象” 来实现,所以,面向对象编程其实就是对 “类” 和 “对象” 的使用。

  类就是一个模板,模板里可以包含多个函数,函数里实现一些功能

  对象则是根据模板创建的实例,通过实例对象可以执行类中的函数

  • class 是关键字,表示类
  • 创建对象,类名称后加括号即可
1
2
3
4
5
6
7
8
9
10
11
12
13
# 创建类
class Foo:
      
    def Bar(self):
        print 'Bar'
  
    def Hello(self, name):
        print 'i am %s' %name
  
# 根据类Foo创建对象obj
obj = Foo()
obj.Bar()            #执行Bar方法
obj.Hello('wupeiqi') #执行Hello方法 

一、封装

封装,顾名思义就是将内容封装到某个地方,以后再去调用被封装在某处的内容。所以,在使用面向对象的封装特性时,需要:

  • 将内容封装到某处
  • 从某处调用被封装的内容

第一步:将内容封装到某处

demo

第二步:从某处调用被封装的内容调用被封装的内容时,有两种情况:

  • 通过对象直接调用
  • 通过 self 间接调用

1、通过对象直接调用被封装的内容上图展示了对象 obj1 和 obj2 在内存中保存的方式,根据保存格式可以如此调用被封装的内容:对象. 属性名 

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self, name, age):
    self.name </span>=<span style="color: rgba(0, 0, 0, 1)"> name
    self.age </span>=<span style="color: rgba(0, 0, 0, 1)"> age

obj1 = Foo('张岩林', 18)
print(obj1.name) # 直接调用 obj1 对象的 name 属性
print(obj1.age) # 直接调用 obj1 对象的 age 属性

obj2
= Foo('Aylin', 18)
print(obj2.name) # 直接调用 obj2 对象的 name 属性
print(obj2.age) # 直接调用 obj2 对象的 age 属性

demo 2、通过 self 间接调用被封装的内容执行类中的方法时,需要通过 self 间接调用被封装的内容

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self,backend):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">构造方法</span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(0, 0, 0, 1)">
    self.backend </span>= backend  <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">普通字段</span>
    self.auther = <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">张岩林</span><span style="color: rgba(128, 0, 0, 1)">"</span>

<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> feach(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(self.backend,<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">作者:</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">,self.auther)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> add(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(self.backend,<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">作者:</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">,self.auther)

#创建对象并把www.baidu.com 封装到对象中
obj = Foo("www.baidu.com")
obj.feach()

obj1 = Foo("www.google.com")
obj1.add()

demo 二、继承继承,面向对象中的继承和现实生活中的继承相同,即:子可以继承父的内容。例如:  猫可以:喵喵叫、吃、喝、拉、撒  狗可以:汪汪叫、吃、喝、拉、撒吃、喝、拉、撒是猫和狗都具有的功能,而我们却分别的猫和狗的类中编写了两次。如果使用 继承 的思想,如下实现:  动物:吃、喝、拉、撒     猫:喵喵叫(猫继承动物的功能)     狗:汪汪叫(狗继承动物的功能)

#继承实例
class Animals:
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> chi(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(self.name+<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">吃</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> he(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(self.name+<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">喝</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> la(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(self.name+<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">拉</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> jiao(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">叫叫</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)

class Uncle:

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> jiao(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">叫叫叫</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)

class dog(Animals,Uncle):

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self,name):
    self.name </span>=<span style="color: rgba(0, 0, 0, 1)"> name

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> jiao(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">叫</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">)

ddog = dog("")
ddog.chi()
ddog.jiao()

demo所以,对于面向对象的继承来说,其实就是将多个类共有的方法提取到父类中,子类仅需继承父类而不必一一实现每个方法。注:除了子类和父类的称谓,你可能看到过 派生类 和 基类 ,他们与子类和父类只是叫法不同而已。 那么问题又来了,多继承呢?

  • 是否可以继承多个类
  • 如果继承的多个类每个类中都定了相同的函数,那么那一个会被使用呢?

1、Python 的类可以继承多个类,Java 和 C# 中则只能继承一个类 

class Zhang(object):
    def f1(self):
        print("zhang")

class A(Zhang):
def f(self):
print("A")

class B(A):
def f(self):
print("B")

class C(Zhang):
def f1(self):
print("C")

class D(C):
def f(self):
print("D")

class E(D,B):
def f(self):
print("E")

ret = E()
ret.f1()

demo 三、多态  Pyhon 不支持多态并且也用不到多态,多态的概念是应用于 Java 和 C# 这一类强类型语言中,而 Python 崇尚“鸭子类型”。

class F1:
    pass

class S1(F1):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> show(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span> (<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">S1.show</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

class S2(F1):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> show(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>( <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">S2.show</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

# 由于在 Java 或 C# 中定义函数参数时,必须指定参数的类型
#
为了让 Func 函数既可以执行 S1 对象的 show 方法,又可以执行 S2 对象的 show 方法,所以,定义了一个 S1 和 S2 类的父类
#
而实际传入的参数是:S1 对象和 S2 对象

def Func(F1 obj):
"""Func 函数需要接收一个 F1 类型或者 F1 子类的类型"""

<span style="color: rgba(0, 0, 255, 1)">print</span><span style="color: rgba(0, 0, 0, 1)"> (obj.show())

s1_obj = S1()
Func(s1_obj)
# 在 Func 函数中传入 S1 类的对象 s1_obj,执行 S1 的 show 方法,结果:S1.show

s2_obj
= S2()
Func(s2_obj)
# 在 Func 函数中传入 Ss 类的对象 ss_obj,执行 Ss 的 show 方法,结果:S2.show

python 伪代码实现 java,c# 多态

class F1:
    pass

class S1(F1):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> show(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span> (<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">S1.show</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

class S2(F1):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> show(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>( <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">S2.show</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

def Func(obj):
print(obj.show())

s1_obj = S1()
Func(s1_obj)

s2_obj = S2()
Func(s2_obj)

python“鸭子类型” 类成员  1、字段:
静态字段:提供给类里每个对象(方法)使用
普通字段:让每个方法都有不同的数据
2、方法:
静态方法: 无需使用对象封装,用类方法执行
类方法: 类方法执行,调用时会显示出当前是哪个类
普通方法: 对象方式执行,使用对象中的数据
3、特性:
可以获取特性 也可以设置特性
一、字段字段包括:普通字段和静态字段,他们在定义和使用中有所区别,而最本质的区别是内存中保存的位置不同,

  • 普通字段属于对象
  • 静态字段属于

class Province:
</span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 静态字段</span>
country = <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">中国</span><span style="color: rgba(128, 0, 0, 1)">'</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self, name):

    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 普通字段</span>
    self.name =<span style="color: rgba(0, 0, 0, 1)"> name

# 直接访问普通字段
obj = Province('河北省')
print(obj.name)

# 直接访问静态字段
Province.country

View Code由上述代码可以看出【普通字段需要通过对象来访问】【静态字段通过类访问】,在使用上可以看出普通字段和静态字段的归属是不同的。其在内容的存储方式类似如下图:注:静态字段只在内存中保存一份,普通字段在每个对象中都要保存一份 二、方法方法包括:普通方法、静态方法和类方法,三种方法在内存中都归属于类,区别在于调用方式不同。  1、普通方法:由对象调用;至少一个self参数;执行普通方法时,自动将调用该方法的对象赋值给self  2、类方法:由调用; 至少一个cls参数;执行类方法时,自动将调用该方法的复制给cls  3、静态方法:由调用;无默认参数;

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self, name):
    self.name </span>=<span style="color: rgba(0, 0, 0, 1)"> name

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> ord_func(self):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 定义普通方法,至少有一个self参数 </span><span style="color: rgba(128, 0, 0, 1)">"""</span>

    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> print self.name</span>
    <span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">普通方法</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

@classmethod
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> class_func(cls):
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 定义类方法,至少有一个cls参数 </span><span style="color: rgba(128, 0, 0, 1)">"""</span>

    <span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">类方法</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

@staticmethod
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> static_func():
    </span><span style="color: rgba(128, 0, 0, 1)">"""</span><span style="color: rgba(128, 0, 0, 1)"> 定义静态方法 ,无默认参数</span><span style="color: rgba(128, 0, 0, 1)">"""</span>

    <span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">静态方法</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

# 调用普通方法
f = Foo()
f.ord_func()

# 调用类方法
Foo.class_func()

# 调用静态方法
Foo.static_func()

定义方法并使用相同点:对于所有的方法而言,均属于类(非对象)中,所以,在内存中也只保存一份。不同点:方法调用者不同、调用方法时自动传入的参数不同。 三、特性  如果你已经了解 Python 类中的方法,那么特性就非常简单了,因为 Python 中的属性其实是普通方法的变种。对于特性,有以下两个知识点:  1、特性的基本使用  2、特性的两种定义方式 1、特性的基本使用

# ############### 定义 ###############
class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> func(self):
    </span><span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 定义特性</span>

@property
def prop(self):
pass
# ############### 调用 ###############
foo_obj = Foo()

foo_obj.func()
foo_obj.prop #调用属性

特性由属性的定义和调用要注意一下几点:  1、定义时,在普通方法的基础上添加 @property 装饰器;  2、定义时,属性仅有一个self 参数  3、调用时,无需括号
           方法:foo_obj.func()
           属性:foo_obj.prop注意:属性存在意义是:访问属性时可以制造出和访问字段完全相同的假象        属性由方法变种而来,如果 Python 中没有属性,方法完全可以代替其功能。实例:对于主机列表页面,每次请求不可能把数据库中的所有内容都显示到页面上,而是通过分页的功能局部显示,所以在向数据库中请求数据时就要显示的指定获取从第 m 条到第 n 条的所有数据(即:limit m,n),这个分页的功能包括:  1、根据用户请求的当前页和总数据条数计算出 m 和 n  2、根据 m 和 n 去数据库中请求数据 

# ############### 定义 ###############
class Pager:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self, current_page):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 用户当前请求的页码(第一页、第二页...)</span>
    self.current_page =<span style="color: rgba(0, 0, 0, 1)"> current_page
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 每页默认显示10条数据</span>
    self.per_items = 10<span style="color: rgba(0, 0, 0, 1)"> 


@property
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> start(self):
    val </span>= (self.current_page - 1) *<span style="color: rgba(0, 0, 0, 1)"> self.per_items
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> val

@property
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> end(self):
    val </span>= self.current_page *<span style="color: rgba(0, 0, 0, 1)"> self.per_items
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> val

# ############### 调用 ###############

p
= Pager(1)
p.start 就是起始值,即:m
p.end 就是结束值,即:n

View Code 2、属性的两种定义方式属性的定义有两种方式:  1、装饰器 即:在方法上应用装饰器  2、静态字段 即:在类中定义值为 property 对象的静态字段 1.1 装饰器方式经典类,具有一种 @property 装饰器

# ############### 定义 ###############    
class Goods:
@property
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> price(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">张岩林</span><span style="color: rgba(128, 0, 0, 1)">"</span>

# ############### 调用 ###############
obj = Goods()
result
= obj.price # 自动执行 @property 修饰的 price 方法,并获取方法的返回值

View Code新式类,具有三种 @property 装饰器

# ############### 定义 ###############
class Goods(object):
@property
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> price(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">@property</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

@price.setter
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> price(self, value):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">@price.setter</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

@price.deleter
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> price(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">@price.deleter</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

# ############### 调用 ###############
obj = Goods()

obj.price # 自动执行 @property 修饰的 price 方法,并获取方法的返回值

obj.price
= 123 # 自动执行 @price.setter 修饰的 price 方法,并将 123 赋值给方法的参数

del obj.price # 自动执行 @price.deleter 修饰的 price 方法

View Code注:1、经典类中的属性只有一种访问方式,其对应被 @property 修饰的方法
     2、新式类中的属性有三种访问方式,并分别对应了三个被 @property、@方法名.setter、@方法名.deleter 修饰的方法由于新式类中具有三种访问方式,我们可以根据他们几个属性的访问特点,分别将三个方法定义为对同一个属性:获取、修改、删除

class Goods(object):
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 原价</span>
    self.original_price = 100
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 折扣</span>
    self.discount = 0.8<span style="color: rgba(0, 0, 0, 1)">

@property
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> price(self):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 实际价格 = 原价 * 折扣</span>
    new_price = self.original_price *<span style="color: rgba(0, 0, 0, 1)"> self.discount
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> new_price

@price.setter
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> price(self, value):
    self.original_price </span>=<span style="color: rgba(0, 0, 0, 1)"> value

@price.deltter
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> price(self, value):
    </span><span style="color: rgba(0, 0, 255, 1)">del</span><span style="color: rgba(0, 0, 0, 1)"> self.original_price

obj = Goods()
obj.price
# 获取商品价格
obj.price = 200 # 修改商品原价
del obj.price # 删除商品原价

View Code 1.2 静态字段方式,创建值为 property 对象的静态字段当使用静态字段的方式创建属性时,经典类和新式类无区别

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> get_bar(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">张岩林</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">

BAR </span>=<span style="color: rgba(0, 0, 0, 1)"> property(get_bar)

obj = Foo()
reuslt
= obj.BAR # 自动调用 get_bar 方法,并获取方法的返回值
print(reuslt)

View Codeproperty 的构造方法中有个四个参数  1、第一个参数是方法名,调用 对象.属性 时自动触发执行方法  2、第二个参数是方法名,调用 对象.属性 = XXX 时自动触发执行方法  3、第三个参数是方法名,调用 del 对象.属性 时自动触发执行方法  4、第四个参数是字符串,调用 对象.属性.__doc__ ,此参数是该属性的描述信息

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> get_bar(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">zhangyanlin</span><span style="color: rgba(128, 0, 0, 1)">'</span>

<span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> *必须两个参数</span>
<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> set_bar(self, value): 
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">set value</span><span style="color: rgba(128, 0, 0, 1)">'</span> +<span style="color: rgba(0, 0, 0, 1)"> value

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> del_bar(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">张岩林</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">

BAR = property(get_bar, set_bar, del_bar, </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">description...</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

obj = Foo()

obj.BAR # 自动调用第一个参数中定义的方法:get_bar
obj.BAR = "aylin" # 自动调用第二个参数中定义的方法:set_bar 方法,并将“aylin”当作参数传入
del Foo.BAR # 自动调用第三个参数中定义的方法:del_bar 方法
obj.BAE.doc # 自动获取第四个参数中设置的值:description...

View Code由于静态字段方式创建属性具有三种访问方式,我们可以根据他们几个属性的访问特点,分别将三个方法定义为对同一个属性:获取、修改、删除

class Goods(object):
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 原价</span>
    self.original_price = 100
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 折扣</span>
    self.discount = 0.8

<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> get_price(self):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 实际价格 = 原价 * 折扣</span>
    new_price = self.original_price *<span style="color: rgba(0, 0, 0, 1)"> self.discount
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> new_price

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> set_price(self, value):
    self.original_price </span>=<span style="color: rgba(0, 0, 0, 1)"> value

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> del_price(self, value):
    </span><span style="color: rgba(0, 0, 255, 1)">del</span><span style="color: rgba(0, 0, 0, 1)"> self.original_price

PRICE </span>= property(get_price, set_price, del_price, <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">价格属性描述...</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

obj = Goods()
obj.PRICE
# 获取商品价格
obj.PRICE = 200 # 修改商品原价
del obj.PRICE # 删除商品原价

View Code所以,定义属性共有两种方式,分别是【装饰器】和【静态字段】,而【装饰器】方式针对经典类和新式类又有所不同。 类成员修饰符 类的所有成员在上一步骤中已经做了详细的介绍,对于每一个类的成员而言都有两种形式:  1、公有成员,在任何地方都能访问  2、私有成员,只有在类的内部才能方法 私有成员和公有成员的定义不同:私有成员命名时,前两个字符是下划线。(特殊成员除外,例如:__init__、__call__、__dict__ 等) 

1
2
3
4
5
class C:
  
    def __init__(self):
        self.name = '公有字段'
        self.__foo = "私有字段"

私有成员和公有成员的访问限制不同 1、静态字段  1、公有静态字段:类可以访问;类内部可以访问;派生类中可以访问  2、私有静态字段:仅类内部可以访问;

class C:
name </span>= <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">公有静态字段</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">

def func(self):
    print(C.name)

class D(C):

def show(self):
    print(C.name)

C.name # 类访问

obj = C()
obj.func() # 类内部可以访问

obj_son = D()
obj_son.show() # 派生类中可以访问

公有字段

class C:
</span><span style="color: rgba(128, 0, 128, 1)">__name</span> = <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">公有静态字段</span><span style="color: rgba(128, 0, 0, 1)">"</span>

<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> func(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(C.<span style="color: rgba(128, 0, 128, 1)">__name</span><span style="color: rgba(0, 0, 0, 1)">)

class D(C):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> show(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(C.<span style="color: rgba(128, 0, 128, 1)">__name</span><span style="color: rgba(0, 0, 0, 1)">)

C.__name # 类访问 ==> 错误

obj
= C()
obj.func()
# 类内部可以访问 ==> 正确

obj_son
= D()
obj_son.show()
# 派生类中可以访问 ==> 错误

私有字段2、普通字段  1、公有普通字段:对象可以访问;类内部可以访问;派生类中可以访问  2、私有普通字段:仅类内部可以访问;注:如果想要强制访问私有字段,可以通过 【对象._ 类名 __ 私有字段明 】访问(如:obj._C__foo),不建议强制访问私有成员。 

class C:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    self.foo </span>= <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">公有字段</span><span style="color: rgba(128, 0, 0, 1)">"</span>

<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> func(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(self.foo)  <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 类内部访问</span>

class D(C):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> show(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span><span style="color: rgba(0, 0, 0, 1)">(self.foo) # 派生类中访问

obj = C()

obj.foo # 通过对象访问
obj.func() # 类内部访问

obj_son
= D();
obj_son.show()
# 派生类中访问

公有字段

class C:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    self.</span><span style="color: rgba(128, 0, 128, 1)">__foo</span> = <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">私有字段</span><span style="color: rgba(128, 0, 0, 1)">"</span>

<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> func(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(self.foo ) <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 类内部访问</span>

class D(C):

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> show(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span><span style="color: rgba(0, 0, 0, 1)">(self.foo) # 派生类中访问

obj = C()

obj.__foo # 通过对象访问 ==> 错误
obj.func() # 类内部访问 ==> 正确

obj_son
= D();
obj_son.show()
# 派生类中访问 ==> 错误

私有字段 类的特殊成员 1、 __doc__  表示类的描述信息

class Foo:
    """ 描述类信息,这是用于看片的神奇 """
<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> func(self):
    </span><span style="color: rgba(0, 0, 255, 1)">pass</span>

print Foo.doc
#输出:类的描述信息

View Code2、 __module__ 和  __class__   __module__ 表示当前操作的对象在那个模块  __class__     表示当前操作的对象的类是什么

#!/usr/bin/env python
# -*- coding:utf-8 -*-

class C:

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    self.name </span>= <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">zhangyanlin</span><span style="color: rgba(128, 0, 0, 1)">'</span></pre>

lib/test.py

from lib.test import C

obj = C()
print obj.module # 输出 lib.aa,即:输出模块
print obj.class # 输出 lib.aa.C,即:输出类

index3、 __init__  构造方法,通过类创建对象时,自动触发执行。 

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self, name):
    self.name </span>=<span style="color: rgba(0, 0, 0, 1)"> name
    self.age </span>= 18<span style="color: rgba(0, 0, 0, 1)">

obj = Foo('张岩林') # 自动执行类中的 init 方法

View Code

class Annimal:
    def __init__(self):
        print("动物构造方法")
        self.name = "动物"

class Dog(Annimal):
def init(self):
print("狗狗构造方法")
self.nn
= ""
super(Dog,self).
init()
# Annimal.init(self)

d = Dog()
print(d.dict)

继承父类 __init__ 4、 __del__  析构方法,当对象在内存中被释放时,自动触发执行。注:此方法一般无须定义,因为 Python 是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给 Python 解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。 

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__del__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(0, 0, 255, 1)">pass</span></pre>

code 5、 __call__  对象后面加括号,触发执行。注:构造方法的执行是由创建对象触发的,即:对象 = 类名 ();而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象 () 或者 类 ()()

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(0, 0, 255, 1)">pass</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__call__</span>(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):

    </span><span style="color: rgba(0, 0, 255, 1)">print</span> (<span style="color: rgba(128, 0, 128, 1)">__call__</span><span style="color: rgba(0, 0, 0, 1)">)

obj = Foo() # 执行 init
obj() # 执行 call

View Code6、 __dict__  类或对象中的所有成员上文中我们知道:类的普通字段属于对象;类中的静态字段和方法等属于类,即:

class Province:
country </span>= <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">China</span><span style="color: rgba(128, 0, 0, 1)">'</span>

<span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self, name, count):
    self.name </span>=<span style="color: rgba(0, 0, 0, 1)"> name
    self.count </span>=<span style="color: rgba(0, 0, 0, 1)"> count

</span><span style="color: rgba(0, 0, 255, 1)">def</span> func(self, *args, **<span style="color: rgba(0, 0, 0, 1)">kwargs):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">func</span><span style="color: rgba(128, 0, 0, 1)">'</span>

# 获取类的成员,即:静态字段、方法、
print Province.dict
# 输出:{'country': 'China', 'module':'main','func': <function func at 0x10be30f50>,'init': <function init at 0x10be30ed8>, 'doc': None}

obj1
= Province('HeBei',10000)
print obj1.dict
# 获取 对象 obj1 的成员
#
输出:{'count': 10000, 'name': 'HeBei'}

obj2
= Province('HeNan', 3888)
print obj2.dict
# 获取 对象 obj1 的成员
#
输出:{'count': 3888, 'name': 'HeNan'}

View Code7、 __str__如果一个类中定义了 __str__ 方法,那么在打印 对象 时,默认输出该方法的返回值。

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__str__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">zhangyanlin</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">

obj = Foo()
print(obj)
# 输出:zhangyanlin

View Code8、__getitem__、__setitem__、__delitem__用于索引操作,如字典。以上分别表示获取、设置、删除数据

class Foo:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__getitem__</span>(self, item):  <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 获取</span>
    <span style="color: rgba(0, 0, 255, 1)">print</span><span style="color: rgba(0, 0, 0, 1)">(item)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__setitem__</span>(self, key, value): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 设置</span>
    <span style="color: rgba(0, 0, 255, 1)">print</span><span style="color: rgba(0, 0, 0, 1)">(key,value)

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__delitem__</span>(self, key): <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 删除</span>
    <span style="color: rgba(0, 0, 255, 1)">print</span><span style="color: rgba(0, 0, 0, 1)">(key)

obj = Foo()

obj["张岩林"] # 调用 getitem
obj["name"]=1234 # 调用 setitem
del obj["namename"] # 调用 delitem
print(Foo.dict)

View Code9、 __iter__ 用于迭代器,之所以列表、字典、元组可以进行 for 循环,是因为类型内部定义了 __iter__ 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

class Foo(object):

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self, sq):
    self.sq </span>=<span style="color: rgba(0, 0, 0, 1)"> sq

</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__iter__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> iter(self.sq)

obj = Foo([11,22,33,44])

for i in obj:
print i

View Code

#!/usr/bin/env python
# -*- coding:utf-8 -*-

obj = iter([11,22,33,44])

while True:
val
= obj.next()
print(val)

for 循环内部语法 单例模式 所谓单例,是指一个类的实例从始至终只能被创建一次。 方法 1如果想使得某个类从始至终最多只有一个实例,使用 __new__ 方法会很简单。Python 中类是通过 __new__ 来创建实例的:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Singleton(object):
    def __new__(cls,*args,**kwargs):
        if not hasattr(cls,'_inst'):
            cls._inst=super(Singleton,cls).__new__(cls,*args,**kwargs)
        return cls._inst
if __name__=='__main__':
    class A(Singleton):
        def __init__(self,s):
            self.s=s    
    a=A('apple'
    b=A('banana')
    print(id(a),a.s)
    print(id(b),b.s)

结果:

1
2
29922256 banana
29922256 banana

通过 __new__ 方法,将类的实例在创建的时候绑定到类属性 _inst 上。如果 cls._inst 为 None,说明类还未实例化,实例化并将实例绑定到 cls._inst,以后每次实例化的时候都返回第一次实例化创建的实例。注意从 Singleton 派生子类的时候,不要重载 __new__。 方法 2当你编写一个类的时候,某种机制会使用类名字,基类元组,类字典来创建一个类对象。新型类中这种机制默认为 type,而且这种机制是可编程的,称为元类 __metaclass__ 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Singleton(type):
    def __init__(self,name,bases,class_dict):
        super(Singleton,self).__init__(name,bases,class_dict)
        self._instance=None
    def __call__(self,*args,**kwargs):
        if self._instance is None:
            self._instance=super(Singleton,self).__call__(*args,**kwargs)
        return self._instance
if __name__=='__main__':
    class A(object):
        __metaclass__=Singleton     
    a=A()
    b=A()
    print(id(a),id(b))

结果:

1
34248016 34248016

id 是相同的。例子中我们构造了一个 Singleton 元类,并使用 __call__ 方法使其能够模拟函数的行为。构造类 A 时,将其元类设为 Singleton,那么创建类对象 A 时,行为发生如下:A=Singleton(name,bases,class_dict),A 其实为 Singleton 类的一个实例。创建 A 的实例时,A()=Singleton(name,bases,class_dict)()=Singleton(name,bases,class_dict).__call__(),这样就将 A 的所有实例都指向了 A 的属性 _instance 上,这种方法与方法 1 其实是相同的。 方法 4最简单的方法:

1
2
3
class singleton(object):
    pass
singleton=singleton()

将名字 singleton 绑定到实例上,singleton 就是它自己类的唯一对象了。 方法 5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class ConnectionPool:
 
    __instance = None
    def __init__(self):
        self.ip = "192.168.1.1"
        self.port = 3306
        self.username = "zhangyanlin"
        self.pwd = 123456
 
    @staticmethod
    def get_instance():
        if ConnectionPool.__instance:
            return ConnectionPool.__instance
        else:
            ConnectionPool.__instance = ConnectionPool()
            return ConnectionPool.__instance
 
obj1 = ConnectionPool()
print(obj1.get_instance())
 
obj2 = ConnectionPool()
print(obj2.get_instance())
 
obj3 = ConnectionPool()
print(obj3.get_instance())

定义静态方法,判断让所有只用第一个对象在内存中创建的 ID