Python之面向对象进阶

  Python之面向对象进阶

    进阶有:Python 类的成员、成员修饰符、类的特殊成员。

一、类的成员

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

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

1、字段

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

  • 普通字段属于对象
  • 静态字段属于
 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 字段的定义和使用
字段的定义和使用

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

由上图可是:

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

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

2、方法

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

  • 普通方法:由对象调用;至少一个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()
28 
29 # 调用类方法
30 Foo.class_func()
31 
32 # 调用静态方法
33 Foo.static_func()
方法的定义和使用

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

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

3、属性  

如果你已经了解Python类中的方法,那么属性就非常简单了,因为Python中的属性其实是普通方法的变种。

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

  • 属性的基本使用
  • 属性的两种定义方式

(1)、属性的基本使用

 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   #调用属性
属性的定义和使用

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

  • 定义时,在普通方法的基础上添加 @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
View Code

从上述可见,Python的属性的功能是:属性内部进行一系列的逻辑计算,最终将计算结果返回。

(2)、属性的两种定义方式

属性的定义有两种方式:

  • 装饰器 即:在方法上应用装饰器
  • 静态字段 即:在类中定义值为property对象的静态字段

装饰器方式:在类的普通方法上应用@property装饰器

我们知道Python中的类有经典类和新式类,新式类的属性比经典类的属性丰富。( 如果类继object,那么该类是新式类 )


经典类,具有一种@property装饰器(如上一步实例)

1 # ############### 定义 ###############    
2 class Goods:
3 
4     @property
5     def price(self):
6         return "wupeiqi"
7 # ############### 调用 ###############
8 obj = Goods()
9 result = obj.price  # 自动执行 @property 修饰的 price 方法,并获取方法的返回值
View Code

 

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

 1 # ############### 定义 ###############
 2 class Goods(object):
 3 
 4     @property
 5     def price(self):
 6         print '@property'
 7 
 8     @price.setter
 9     def price(self, value):
10         print '@price.setter'
11 
12     @price.deleter
13     def price(self):
14         print '@price.deleter'
15 
16 # ############### 调用 ###############
17 obj = Goods()
18 
19 obj.price          # 自动执行 @property 修饰的 price 方法,并获取方法的返回值
20 
21 obj.price = 123    # 自动执行 @price.setter 修饰的 price 方法,并将  123 赋值给方法的参数
22 
23 del obj.price      # 自动执行 @price.deleter 修饰的 price 方法
View Code

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

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

 1 class Goods(object):
 2 
 3     def __init__(self):
 4         # 原价
 5         self.original_price = 100
 6         # 折扣
 7         self.discount = 0.8
 8 
 9     @property
10     def price(self):
11         # 实际价格 = 原价 * 折扣
12         new_price = self.original_price * self.discount
13         return new_price
14 
15     @price.setter
16     def price(self, value):
17         self.original_price = value
18 
19     @price.deltter
20     def price(self, value):
21         del self.original_price
22 
23 obj = Goods()
24 obj.price         # 获取商品价格
25 obj.price = 200   # 修改商品原价
26 del obj.price     # 删除商品原价
实例

 

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

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

 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
View Code

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

  • 第一个参数是方法名,调用 对象.属性 时自动触发执行方法
  • 第二个参数是方法名,调用 对象.属性 = XXX 时自动触发执行方法
  • 第三个参数是方法名,调用 del 对象.属性 时自动触发执行方法
  • 第四个参数是字符串,调用 对象.属性.__doc__ ,此参数是该属性的描述信息
 1 class Foo:
 2 
 3     def get_bar(self):
 4         return 'wupeiqi'
 5 
 6     # *必须两个参数
 7     def set_bar(self, value): 
 8         return return 'set value' + value
 9 
10     def del_bar(self):
11         return 'wupeiqi'
12 
13     BAR = property(get_bar, set_bar, del_bar, 'description...')
14 
15 obj = Foo()
16 
17 obj.BAR              # 自动调用第一个参数中定义的方法:get_bar
18 obj.BAR = "alex"     # 自动调用第二个参数中定义的方法:set_bar方法,并将“alex”当作参数传入
19 del Foo.BAR          # 自动调用第三个参数中定义的方法:del_bar方法
20 obj.BAE.__doc__      # 自动获取第四个参数中设置的值:description...
View Code

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

 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     # 删除商品原价
实例

注意: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)
Django源码

所以,定义属性共有两种方式,分别是【装饰器】和【静态字段】,而【装饰器】方式针对经典类和新式类又有所不同。

 

posted @ 2018-03-10 20:13  王先生是胖子  阅读(151)  评论(0编辑  收藏  举报