上一篇文章介绍了面向对象基本知识:

  • 面向对象是一种编程方式,此编程方式的实现是基于对  和 对象 的使用
  • 类 是一个模板,模板中包装了多个“函数”供使用(可以讲多函数中公用的变量封装到对象中)
  • 对象,根据模板创建的实例(即:对象),实例用于调用被包装在类中的函数
  • 面向对象三大特性:封装、继承和多态

 本篇将详细介绍Python 类的成员、成员修饰符、类的特殊成员。

注意点:

  self ,我们讲过了,self = 对象,实例化后的对象调用类的各种成员的时候的self就是这个对象。

  而且我们也讲过了继承的查找顺序,因此,遇到self 就要从对象的类 开始往上找 

 1 #遇到self就要对象实例化的开始的类里面一层一层往上查找
 2 
 3 # 这里 d继承cb  b继承a  所以 d 继承 c b a 所有的方法,  
 4 # D() 类实例化会找init ,d中没有,找b ,b中没有找a都没有在执行 d1.bar()   查找 顺序和上面的一样。
而bar方法也有个self.f1,就要从头开始 找了,遇到第一个f1 就执行了
5 class A: 6 def bar(self): 7 print("bar") 8 self.f1() 9 class B(A): 10 def f1(self): 11 self.bar() 12 class C: 13 def f1(self): 14 print("c") 15 16 class D(C,B): 17 pass 18 d1 = D() 19 d1.bar() 20 21 遇到self就要对象实例化的开始的类里面一层一层往上查找

 

SUPER或  父类.__Init(self)

子类有init方法,父类也有init方法和各种属性,,要想让子类也 继承并封装父类的init的属性。

super 推荐 ,父类.__Init(self) 不推荐

 1 class Animal:
 2     def __init__(self):
 3         print("a的构造方法")
 4         self.a = "动物"
 5  
 6  
 7 class Cat(Animal):
 8     def __init__(self):
 9         print("b的构造方法")
10         self.b = "mao"
11         super(Cat, self).__init__() # 推荐这种 继承父类的init所有属性 记住self的位置。由super解决
12         # Animal.__init__(self)  # 这种方法不推荐,容易混乱
13  
14  
15  
16 c1 = Cat()
17 print(c1.__dict__)
# 查找一遇到 self 就要从头开始找


 1 import socketserver
 2 r = socketserver.ThreadingTCPServer()
 3 r.serve_forever()
 4 
 5 socketserver 是模块
 6 ThreadingTCPServer 是类
 7 ThreadingTCPServer 继承了两个类
 8 
 9 class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
10 而 r被类实例化的时候,需要一一找 init 
11 ThreadingMixIn  没有,而TCPServer有init
12 但是有一个BaseServer.__init__(self, server_address, RequestHandlerClass)
13 TCPServer 继承了 BaseServer,所以BaseServer的init也会执行,一步一步走
14 
15 r.serve_forever() 对象的方法执行,
16 遇到self 一步一步往上找 只有BaseServer 存在该方法
17 self._handle_request_noblock()  遇到self 一步一步往上走
18 
19 self.process_request(request, client_address) 
20 现在找process_request
21 
22 class ThreadingMixIn:
23 
24     def process_request(self, request, client_address):
25 
26 
27 
28 
29 先找到了第一个类
30 
31 练习查找看程序走到哪一步了。
# 反射 对象 类的两种
 1 # 反射 对象 类的两种
 2 class Do:
 3     def __init__(self, name):
 4         self.name = name
 5 
 6     def show(self):
 7         print("show")
 8 
 9 
10 obj = Do("kakaka")
11 # 反射 传入类的时候,只能找到类的成员
12 # r = hasattr(Do, "show")  # True
13 r = hasattr(Do, "name")#name是对象的成员。
14 print(r)
15 print(Do.__dict__)
16 
17 # 反射传入对象 ,可以通过类对象指针找到类的方法 既可以找到对象的属性 也可以通过对象找到类中的方法,因为有类对象指针
18 x = hasattr(obj, "name")
19 print(x)
20 print(obj.__dict__)
21 y = hasattr(obj, "show")
22 print(y)
23 
24 ======================
25 False
26 {'__dict__': <attribute '__dict__' of 'Do' objects>, 'show': <function Do.show at 0x0000016C8355D400>, '__init__': <function Do.__init__ at 0x0000016C8355D378>, '__weakref__': <attribute '__weakref__' of 'Do' objects>, '__doc__': None, '__module__': '__main__'}
27 True
28 {'name': 'kakaka'}
29 True
 1 #导入模块
 2 m=__import__("s2",fromlist=True)
 3 #去模块中找类
 4 class_name=getattr(m,"Do")
 5 print(class_name)
 6 #根据模块创建对象
 7 obj=class_name("alex")
 8 #去对象中找name对应的值
 9 m=getattr(obj,"name")
10 print(m)
1 #s2.py
2 class Do:
3     def __init__(self, name):
4         self.name = name
5 
6     def show(self):
7         print("show")

 

二   类的成员

类的成员可以分为三大类:字段、方法和属性

python基础-9.1 面向对象进阶 super 类对象成员 类属性 私有属性 查找源码类对象步骤 类特殊成员 isinstance issubclass 异常处理

注:所有成员中,只有普通字段的内容保存对象中,即:根据此类创建了多少对象,在内存中就有多少个普通字段。而其他的成员,则都是保存在类中,即:无论对象的多少,在内存中只创建一份。

一、字段

字段包括:普通字段和静态字段,他们在定义和使用中有所区别,而最本质的区别是内存中保存的位置不同,

  • 普通字段属于对象
  • 静态字段属于
 1 class Province:
 2 
 3     # 静态字段
 4     country = '中国'
 5 
 6     def __init__(self, name):
 7 
 8         # 普通字段
 9         self.name = name
10 
11 
12 # 直接访问普通字段
13 obj = Province('河北省')
14 print obj.name
15 
16 # 直接访问静态字段
17 Province.country
18 
19 字段的定义和使用
20 
21 静态字段 普通字段 定义位置和访问方式

由上述代码可以看出【普通字段需要通过对象来访问】【静态字段通过类访问】,在使用上可以看出普通字段和静态字段的归属是不同的。其在内容的存储方式类似如下图:

python基础-9.1 面向对象进阶 super 类对象成员 类属性 私有属性 查找源码类对象步骤 类特殊成员 isinstance issubclass 异常处理

由上图可是:

  • 静态字段在内存中只保存一份
  • 普通字段在每个对象中都要保存一份

应用场景: 通过类创建对象时,如果每个对象都具有相同的字段,那么就使用静态字段

字段总结:

# 规范:谁里面的东西谁自己访问
# 类变量  静态 字段, 用于保存在类中,减少 重复变量赋值使用
# 构造函数变量 普通字段
# 类方法: 普通方法

成员:
  通过类访问有:静态字段
  通过对象访问有:普通字段、类的方法。
 1    # 类变量  静态 字段, 用于保存在类中,减少 重复变量赋值使用
 2     # 构造函数变量 普通字段
 3     # 类方法: 普通方法
 4  
 5 class Foo:
 6  
 7     country = "zhongguo "#静态字段,类中
 8  
 9     def __init__(self,name):
10         self.name = name  #普通字段,对象中
11         # name = name     # 找不到
12  
13     def show(self):
14         print("show")
15   
16 # 获取静态字段
17 print(Foo.country) ## 规范:1、谁里面的东西谁自己访问,2、除了类中的方法
18  
19 obj = Foo("liujianzuo")
20 x = hasattr(obj,"name")#判断对象中的name字段值
21  
22 y = hasattr(obj,"show")
23 print(x,y)

 

二、方法

方法包括:普通方法、静态方法和类方法,三种方法在内存中都归属于类,区别在于调用方式不同。

  • 普通方法:由对象调用;至少一个self参数;执行普通方法时,自动将调用该方法的对象赋值给self
  • 类方法:由调用; 至少一个cls参数;执行类方法时,自动将调用该方法的类赋值cls
  • 静态方法:由调用;无默认参数;
 1 class Foo:
 2 
 3     def __init__(self, name):
 4         self.name = name
 5 
 6     def ord_func(self):
 7         """ 定义普通方法,至少有一个self参数 """
 8 
 9         print self.name
10         print '普通方法'
11 
12     @classmethod
13     def class_func(cls):
14         """ 定义类方法,至少有一个cls参数 """
15 
16         print '类方法'
17 
18     @staticmethod
19     def static_func():
20         """ 定义静态方法 ,无默认参数"""
21 
22         print '静态方法'
23 
24 
25 # 调用普通方法
26 f = Foo()
27 f.ord_func("Alex")
28 
29 # 调用类方法
30 Foo.class_func()
31 
32 # 调用静态方法
33 Foo.static_func()
34 
35 方法的定义和使用
36 
37 普通方法 类方法 静态方法区别

python基础-9.1 面向对象进阶 super 类对象成员 类属性 私有属性 查找源码类对象步骤 类特殊成员 isinstance issubclass 异常处理

相同点:对于所有的方法而言,均属于类(非对象)中,所以,在内存中也只保存一份

不同点:方法调用者不同、调用方法时自动传入的参数不同。

2.1 类中 各个方法的规范

"""
# **********类 对象 ===》静态字段 静态方法 普通字段 类方法 普通方法***********
#规范:
# 注: 静态方法没有self ,该传多少参数传多少参数
通过类访问有: 静态字段,静态方法、类方法
通过对象访问:普通字段 普通方法
# 上面是规范,当然 通过对象访问静态字段也能访问到。
"""

2.2 静态方法访问

 1 # 静态方法
 2 """
 3 # **********类 对象 ===》静态字段  静态方法  普通字段  类方法 普通方法***********
 4     #规范:
 5         # 注: 静态方法没有self ,该传多少参数传多少参数
 6         通过类访问有: 静态字段,静态方法,类方法 
 7         通过对象访问:普通字段 普通方法
 8         # 上面是规范,当然 通过对象访问静态字段也能访问到。
 9 """
10  
11 class Foo:
12  
13     country = "zhongguo "#静态字段
14  
15     def __init__(self,name):
16         self.name = name  # 普通字段
17         # name = name     # 找不到
18     @staticmethod #类似一个函数,不需要 创建对象就能访问这个方法。  当然通过创建对象也可以访问这个方法。这个静态方法没有self .由于java c# 没有函数式编程,这里用到静态方法,相当于在类里面谢了一个函数,不用创建对象就能执行这个方法,因此java c#也可以函数式编程了
19     def cat(arg1,arg2):
20         print(arg1,arg2)
21  
22     def show(self):
23         print("show")
24 # 静态方法 访问 1  不推荐
25 #当然通过创建对象也可以访问这个方法
26 obj = Foo("liujianzuo")
27 obj.cat(111,222)
28  
29 # 静态方法访问 2 推荐  类.方法
30 # 参数不用写self 可传入多个参数
31 Foo.cat("num1","num2")

2.3 类方法 访问   静态方法的特殊情况方法,无self

 1 # 类方法
 2  
 3 class Foo:
 4  
 5     country = "zhongguo "
 6  
 7     def __init__(self,name):
 8         self.name = name  # 普通字段
 9         # name = name     # 找不到
10  
11     @classmethod  #  类方法 必须传入cls 也就是 类名   即 类名.cat()
12     def cat(cls):
13  
14         print(cls)
15  
16     def show(self):
17         print("show")
18  
19  
20 Foo.cat()

三、属性 即 特性 property 

如果你已经了解Python类中的方法,那么属性就非常简单了,因为Python中的属性其实是普通方法的变种。调用的时候不用加(),和获取对象的字段类似。

对于属性,有以下三个知识点:

  • 属性的基本使用
  • 属性的两种定义方式
#特性  @propety可以使用对象像访问字段一样访问这个方法。调用的时候不用加(),和获取对象的字段类似。
#     @特性方法名.setter   设置 方法的返回值

特性 property 和 property setter 可以控制向访问普通字段一样访问 方法
 1 #特性  @propety可以使用对象向访问字段一样访问这个方法。
 2 class Foo:
 3 
 4     country = "zhongguo "
 5 
 6     def __init__(self,name):
 7         self.name = name  # 普通字段
 8         # name = name     # 找不到

9 #将方法伪造成字段 10 @property # 特性。 可以当做字段让对象调用,调用时就不用加() 11 def cat(self): #不能加参数,加了就报错 12 temp = "%s sb"% self.name 13 print(temp) 14 return temp 15 16 def show(self): 17 print("show") 18 19 obj = Foo("LIUJIANZUO") 20 print(obj.name) 21 print(obj.cat) 22
 1 #@特性方法名.setter   设置 方法的返回值
 2 class Foo:
 3     country = "zhongguo "
 4 
 5     def __init__(self, name):
 6         self.name = name  # 普通字段
 7         # name = name     # 找不到
 8 
 9     @property  # 特性。 可以当做字段让对象调用
10     def cat(self):
11         temp = "%s sb" % self.name
12         print(temp)
13         return(temp)
14 
15 
16     @cat.setter  # 这个cat函数用来设置值的。
17     def cat(self, value):
18         self.name = value #重新设置self.name
19         print(value)
20 
21 
22     def show(self):
23         print("show")
24 
25 
26 obj = Foo("LIUJIANZUO")
27 ret = obj.cat #第一次调用
28 print(ret) #输出返回值
29 obj.cat = "new_name"#修改返回值
30 ret=obj.cat #第二次调用
31 print(ret) #再次输出返回值
32 # 特性 property 和 property setter 可以控制向访问普通字段一样访问 方法

 

项目案例: property两种不同的调用方式

 1 # @property #此方法调用 UserType(nid=db_result['user_type']).get_caption
 2     def get_caption(self):
 3         caption = None
 4  
 5         for item in VipType.VIP_TYPE:
 6             if item['nid'] == self.nid:
 7                 caption = item['caption']
 8                 break
 9         return caption
10  
11     caption = property(get_caption)  # 此方法调用 VipType(nid=db_result['vip']).caption
12  
13  
14 调用vipcap= VipType(nid=db_result['vip']).caption 这是caption = property(get_caption)这种方法 用的是返回字段名
15  
16 UserType(nid=db_result['user_type']).get_caption 这是@装饰器属性方法

1、属性的基本使用

property 装饰函数调用的时候用类调用,并且执行无需创建对象,也不用加括号 

 1 # ############### 定义 ###############
 2 class Foo:
 3  
 4     def func(self):
 5         pass
 6  
 7     # 定义属性
 8     @property
 9     def prop(self):
10         pass
11 # ############### 调用 ###############
12 foo_obj = Foo()
13  
14 foo_obj.func()
15 foo_obj.prop   #调用属性
16  
17 属性的定义和使用

python基础-9.1 面向对象进阶 super 类对象成员 类属性 私有属性 查找源码类对象步骤 类特殊成员 isinstance issubclass 异常处理

由属性(特性)的定义和调用要注意一下几点:

  • 定义时,在普通方法的基础上添加 @property 装饰器;
  • 定义时,属性仅有一个self参数,不能加其他参数。
  • 调用时,无需括号
               方法:foo_obj.func()
               属性:foo_obj.prop

注意:属性存在意义是:访问属性时可以制造出和访问字段完全相同的假象

        属性由方法变种而来,如果Python中没有属性,方法完全可以代替其功能。

 

实例练习:对于主机列表页面,每次请求不可能把数据库中的所有内容都显示到页面上,而是通过分页的功能局部显示,所以在向数据库中请求数据时就要显示的指定获取从第m条到第n条的所有数据(即:limit m,n),这个分页的功能包括:

      • 根据用户请求的当前页和总数据条数计算出 m 和 n
      • 根据m 和 n 去数据库中请求数据 
 1 # ############### 定义 ###############
 2 class Pager:
 3      
 4     def __init__(self, current_page):
 5         # 用户当前请求的页码(第一页、第二页...)
 6         self.current_page = current_page
 7         # 每页默认显示10条数据
 8         self.per_items = 10
 9  
10  
11     @property
12     def start(self):
13         val = (self.current_page - 1) * self.per_items
14         return val
15  
16     @property
17     def end(self):
18         val = self.current_page * self.per_items
19         return val
20  
21 # ############### 调用 ###############
22  
23 p = Pager(1)
24 p.start 就是起始值,即:m
25 p.end   就是结束值,即:n
从上述可见,Python的属性的功能是:属性内部进行一系列的逻辑计算,最终将计算结果返回。

2、属性的两种定义方式

属性的定义有两种方式:

  • 装饰器 即:在方法上应用装饰器
  • 静态字段 即:在类中定义值为property对象的静态字段
装饰器方式:在类的普通方法上应用@property装饰器
我们知道Python中的类有经典类和新式类,新式类的属性比经典类的属性丰富。( 如果类继object,那么该类是新式类 )
经典类,具有一种@property装饰器(如上一步实例)
# ############### 定义 ###############   
class Goods:
 
    @property
    def price(self):
        return "wupeiqi"
# ############### 调用 ###############
obj = Goods()
result = obj.price  # 自动执行 @property 修饰的 price 方法,并获取方法的返回值
新式类,具有三种@property装饰器
# ############### 定义 ###############
class Goods(object):
 
    @property
    def price(self):
        print '@property'
 
    @price.setter
    def price(self, value):
        print '@price.setter'
 
    @price.deleter
    def price(self):
        print '@price.deleter'
 
# ############### 调用 ###############
obj = Goods()
 
obj.price          # 自动执行 @property 修饰的 price 方法,并获取方法的返回值
 
obj.price = 123    # 自动执行 @price.setter 修饰的 price 方法,并将  123 赋值给方法的参数
 
del obj.price      # 自动执行 @price.deleter 修饰的 price 方法

注:经典类中的属性只有一种访问方式,其对应被 @property 修饰的方法
      新式类中的属性有三种访问方式,并分别对应了三个被@property、@方法名.setter、@方法名.deleter修饰的方法

由于新式类中具有三种访问方式,我们可以根据他们几个属性的访问特点,分别将三个方法定义为对同一个属性:获取、修改、删除

class Goods(object):
 
    def __init__(self):
        # 原价
        self.original_price = 100
        # 折扣
        self.discount = 0.8
 
    @property
    def price(self):
        # 实际价格 = 原价 * 折扣
        new_price = self.original_price * self.discount
        return new_price
 
    @price.setter
    def price(self, value):
        self.original_price = value
 
    @price.deltter
    def price(self, value):
        del self.original_price
 
obj = Goods()
obj.price         # 获取商品价格
obj.price = 200   # 修改商品原价
del obj.price     # 删除商品原价
 
实例

静态字段方式,创建值为property对象的静态字段  

 1 当使用静态字段的方式创建属性时,经典类和新式类无区别

# 自动调用get_bar方法,并获取方法的返回值

 1 class Foo:
 2 
 3     def get_bar(self):
 4         return 'wupeiqi'
 5 
 6     BAR = property(get_bar)
 7 
 8 obj = Foo()
 9 reuslt = obj.BAR        # 自动调用get_bar方法,并获取方法的返回值
10 print reuslt
11 
12 # 自动调用get_bar方法,并获取方法的返回值

property的构造方法中有个四个参数

  • 第一个参数是方法名,调用 对象.属性 时自动触发执行方法
  • 第二个参数是方法名,调用 对象.属性 = XXX 时自动触发执行方法
  • 第三个参数是方法名,调用 del 对象.属性 时自动触发执行方法
  • 第四个参数是字符串,调用 对象.属性.__doc__ ,此参数是该属性的描述信息

set del get 等property方法

class Foo:

    def get_bar(self):
        return 'wupeiqi'

    # *必须两个参数
    def set_bar(self, value): 
        return return 'set value' + value

    def del_bar(self):
        return 'wupeiqi'

    BAR = property(get_bar, set_bar, del_bar, 'description...')

obj = Foo()

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

set del get 等property方法

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

 1 class Goods(object):
 2 
 3     def __init__(self):
 4         # 原价
 5         self.original_price = 100
 6         # 折扣
 7         self.discount = 0.8
 8 
 9     def get_price(self):
10         # 实际价格 = 原价 * 折扣
11         new_price = self.original_price * self.discount
12         return new_price
13 
14     def set_price(self, value):
15         self.original_price = value
16 
17     def del_price(self, value):
18         del self.original_price
19 
20     PRICE = property(get_price, set_price, del_price, '价格属性描述...')
21 
22 obj = Goods()
23 obj.PRICE         # 获取商品价格
24 obj.PRICE = 200   # 修改商品原价
25 del obj.PRICE     # 删除商品原价
26 
27 实例
28 
29 代码案例

注意:Python WEB框架 Django 的视图中 request.POST 就是使用的静态字段的方式创建的属性

 1 class WSGIRequest(http.HttpRequest):
 2     def __init__(self, environ):
 3         script_name = get_script_name(environ)
 4         path_info = get_path_info(environ)
 5         if not path_info:
 6             # Sometimes PATH_INFO exists, but is empty (e.g. accessing
 7             # the SCRIPT_NAME URL without a trailing slash). We really need to
 8             # operate as if they'd requested '/'. Not amazingly nice to force
 9             # the path like this, but should be harmless.
10             path_info = '/'
11         self.environ = environ
12         self.path_info = path_info
13         self.path = '%s/%s' % (script_name.rstrip('/'), path_info.lstrip('/'))
14         self.META = environ
15         self.META['PATH_INFO'] = path_info
16         self.META['SCRIPT_NAME'] = script_name
17         self.method = environ['REQUEST_METHOD'].upper()
18         _, content_params = cgi.parse_header(environ.get('CONTENT_TYPE', ''))
19         if 'charset' in content_params:
20             try:
21                 codecs.lookup(content_params['charset'])
22             except LookupError:
23                 pass
24             else:
25                 self.encoding = content_params['charset']
26         self._post_parse_error = False
27         try:
28             content_length = int(environ.get('CONTENT_LENGTH'))
29         except (ValueError, TypeError):
30             content_length = 0
31         self._stream = LimitedStream(self.environ['wsgi.input'], content_length)
32         self._read_started = False
33         self.resolver_match = None
34 
35     def _get_scheme(self):
36         return self.environ.get('wsgi.url_scheme')
37 
38     def _get_request(self):
39         warnings.warn('`request.REQUEST` is deprecated, use `request.GET` or '
40                       '`request.POST` instead.', RemovedInDjango19Warning, 2)
41         if not hasattr(self, '_request'):
42             self._request = datastructures.MergeDict(self.POST, self.GET)
43         return self._request
44 
45     @cached_property
46     def GET(self):
47         # The WSGI spec says 'QUERY_STRING' may be absent.
48         raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '')
49         return http.QueryDict(raw_query_string, encoding=self._encoding)
50     
51     # ############### 看这里看这里  ###############
52     def _get_post(self):
53         if not hasattr(self, '_post'):
54             self._load_post_and_files()
55         return self._post
56 
57     # ############### 看这里看这里  ###############
58     def _set_post(self, post):
59         self._post = post
60 
61     @cached_property
62     def COOKIES(self):
63         raw_cookie = get_str_from_wsgi(self.environ, 'HTTP_COOKIE', '')
64         return http.parse_cookie(raw_cookie)
65 
66     def _get_files(self):
67         if not hasattr(self, '_files'):
68             self._load_post_and_files()
69         return self._files
70 
71     # ############### 看这里看这里  ###############
72     POST = property(_get_post, _set_post)
73     
74     FILES = property(_get_files)
75     REQUEST = property(_get_request)
76 
77 Django源码
78 
79 django源码
Django源码

相关文章:

  • 2021-07-06
  • 2021-05-16
  • 2022-01-08
  • 2021-12-09
  • 2021-09-16
  • 2022-02-15
  • 2021-07-21
  • 2021-10-28
猜你喜欢
  • 2022-01-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-27
  • 2021-11-30
  • 2021-05-29
相关资源
相似解决方案