类的成员
类的成员可以分为三类:字段、方法和属性
注:所有成员中,只是普通字段的内容保存对象中,即:根据此类创建了多少对象,在内存中就有多少个普通字段。而其他的成员,则都是保存在类中,即:无论多少对象,在内存中只创建一份。
一、字段
字段包括:普通字段和静态字段,它们在定义和使用中有所区别,而最本质的区别是在内存中保存的位置不同
- 普通字段属于对象
- 静态字段属于类
class Province:
#静态字段
country = '中国'
def __init__(self,name):
#普通字段
self.name = name
访问普通字段
>>> p = Province('河北省')
>>> p.name
'河北省'
>>>
访问静态字段
>>> Province.country
'中国'
由以上代码可以看出【普通字段需要通过对象来访问】【静态字段通过类来访问】,
在使用上可以看出普通字段和静态字段的归属是不同的。其在内容的存储方式类似如下图:
由上图可知:
- 静态字段在内存中只保存一份
- 普通字段在每个对象中都要保存一份
二、方法
方法包括:普通方法、静态方法和类方法,三种方法在内存中都归属于类,区别在于调用方式不同。
- 普通方法:由对象调用;至少一个self参数;执行普通方法时,自动将调用该方法的对象赋值给self;
- 类方法:由类调用;至少一个cls参数;执行类方法时,自动将调用该方法的类复制给cls;
- 静态方法:由类调用;无默认参数;
class Foo:
def __init__(self,name):
self.name = name
def ord_func(self):
print('普通方法')
@classmethod
def class_func(cls):
print('类方法')
@staticmethod
def static_func():
print('静态方法')
调用普通方法
>>> f = Foo('属性')
>>> f.ord_func()
普通方法
调用类方法
>>> Foo.class_func()
类方法
调用静态方法
>>> Foo.static_func()
静态方法
>>>
![Python-31 面向对象:进阶 Python-31 面向对象:进阶](https://image.shishitao.com:8440/aHR0cHM6Ly93d3cuaXRkYWFuLmNvbS9nby9hSFIwY0RvdkwybHRaeTVpYkc5bkxtTnpaRzR1Ym1WMEx6SXdNVGN3T0RFME1ESXpOVFE0TVRreg%3D%3D.jpg?w=700)
相同点:对于所有的方法而言,均属于(非对象)中,在内存中也只保存一份。
不同点:方法调用者不同、调用方法时自动传入的参数不用。
三、属性
如果你已经了解了Python类中的方法,那么属性就非常简单了,因为Python中的属性其实是普通方法的变种。
对于属性,有以下三个知识点:
- 属性的基本使用
- 属性的两种定义方式
1、属性的基本应用
class Foo:
def func(self):
pass
@property
def prop(self):
print('属性')
调用
>>> Foo.prop
<property object at 0x0200B4E0>
>>> f = Foo()
>>> f.prop
属性
>>>
![Python-31 面向对象:进阶 Python-31 面向对象:进阶](https://image.shishitao.com:8440/aHR0cHM6Ly93d3cuaXRkYWFuLmNvbS9nby9hSFIwY0RvdkwybHRaeTVpYkc5bkxtTnpaRzR1Ym1WMEx6SXdNVGN3T0RFME1ESTFNalF3T0RFMQ%3D%3D.jpg?w=700)
由属性的定义和调用要注意以下几点:
- 定义时,在普通方法的基础上添加@property装饰器
- 定义时,属性仅有一个self参数
- 调用时,无需括号
- 方法:f.func()
- 属性:f.prop
属性由方法变种而来,如果Python中没有属性,方法完全可以代替其功能。
实例:对于主机列表页面,每次请求不可能把数据库中的所有内容都显示到页面上,而是通过分页的功能局部显示, 所以在向数据库中请求数据时就要显示的指定获取从第m条到第n条的所有数据(即:limit m,n),这个分页的功能包括:
- 根据用户请求的当前页和总条数计算出m和n
- 根据m和n去数据库中请求数据
class Pager:
def __init__(self,current_page):
#用户当前请求的页码(第一页、第二页...)
self.current_page = current_page
#每页默认显示10条
self.per_items = 10
@property
def start(self):
val = (self.current_page-1)*self.per_items
return val
@property
def end(self):
val = (self.current_page)*self.per_items
return val
############调用##############
>>> p = Pager(10)
>>> p.start
90
>>> p.end
100
>>>
由上可见,Python的属性的功能是:属性内部进行一系列的计算,最终将计算结果返回。
2、属性的两种定义方式
属性的两种定义方式:
- 装饰器 即:在方法上应用装饰器
- 静态字段 即:在类中定义值为property对象的静态字段
装饰器方式:在类的普通方法上应用@property装饰器
我们知道Python中的类有经典类和新式类,新式类的属性比经典类的属性丰富。(如果类继承object,那么该类是新式类)
经典类,具有一种@property装饰器(如上一步实例)
#########定义##########
class Goods:##########调用############
@property
def price(self):
return 'goods'
>>> go = Goods()
>>> go.price #自动执行@property修饰的price方法,并获取方法的返回值
'goods'
>>>
新式类,具有三种@property装饰器
######定义########
class Goods(object):
@property
def price(self):
return 'goods'
@price.setter
def price(self,value):
print('price.setter:%d' % value)
@price.deleter
def price(self):
print('price.deleter')
######调用######
>>> g = Goods()
>>> g.price #自动执行@property修饰的price方法,并获取方法的返回值
'goods'
>>> g.price = 123 #自动执行@price.setter修饰的price方法,并将123赋值给方法的参数
price.setter:123
>>> del g.price #自动执行@price.deleter修饰的price方法
price.deleter
>>>
注:经典类中的属性只有一种访问方式,其对应被@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.deleter
def price(self):
del self.original_price
>>> g = Goods()
>>> g.price #获取商品价格
80.0
>>> g.price = 200 #修改商品价格
>>> g.original_price
200
>>> g.price
160.0
>>> del g.price #删除商品价格
静态字段方式,创建值为property对象的静态字段
当时用静态字段的方式创建属性时,经典类和新式类无区别
class Foo:
def get_bar(self):
return 'wupei'
BAR = property(get_bar)
>>> f = Foo()
>>> f.BAR #自动调用get_bar方法,并获取方法的返回值
'wupei'
>>>
>>> f.BAR.__doc__
"str(object='') -> str\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\n\nCreate a new string object from the given object. If encoding or\nerrors is specified, then the object must expose a data buffer\nthat will be decoded using the given encoding and error handler.\nOtherwise, returns the result of object.__str__() (if defined)\nor repr(object).\nencoding defaults to sys.getdefaultencoding().\nerrors defaults to 'strict'."
>>>
- 第一个参数是方法名,调用 对象.属性 时自动触发执行方法
- 第二个参数是方法名,调用 对象.属性 = xxx 时自动触发执行方法
- 第三个参数是方法名,调用 del 对象.属性 时自动触发执行方法
- 第四个参数是字符串,调用 类.属性.__doc__,此参数是该属性的描述信息
class Foo:
def get_bar(self):
print('get_bar')
def set_bar(self,value):
print('set_bar')
def del_bar(self):
print('del_bar')
BAR = property(get_bar,set_bar,del_bar,"this is description.....")
>>> f = Foo()
>>> f.BAR #自动调用第一个参数中定义的方法:get_bar
get_bar
>>> f.BAR = 'sdf' #自动调用第二个参数中定义的方法:set_bar方法,并将sdf当做参数传入
set_bar
>>> del f.BAR #自动调用第三个参数中定义的方法:del_bar方法
del_bar
>>> Foo.BAR.__doc__ #自动获取第四个参数中设置的值:this is description
'this is description.....'
>>>
由于静态字段方式创建属性具有三种访问方式,我们可以根据他们几个属性的访问特点,分别将三个方法定义为对同一属性的:
获取、修改、删除
class Goods(object):
def __init__(self):
self.original_price = 100
self.discount = 0.8
def get_price(self):
new_price = self.original_price*self.discount
return new_price
def set_price(self,value):
self.original_price = value
def del_price(self):
del self.original_price
PIRCE = property(get_price,set_price,del_price,'价格描述.....')
>>> g = Goods()
>>> g.PIRCE #获取商品价格
80.0
>>> g.PIRCE = 200 #修改商品价格
>>> g.PIRCE
160.0
>>> del g.PIRCE #删除商品价格
>>> g.PIRCE = 200
>>> g.original_price
200
>>> Goods.PIRCE.__doc__
'价格描述.....'
>>>
注意:Python WEB框架Django的视图中request.POST就是使用静态字段的方式创建的属性
class WSGIRequest(http.HttpRequest):
def __init__(self, environ):
script_name = get_script_name(environ)
path_info = get_path_info(environ)
if not path_info:
# Sometimes PATH_INFO exists, but is empty (e.g. accessing
# the SCRIPT_NAME URL without a trailing slash). We really need to
# operate as if they'd requested '/'. Not amazingly nice to force
# the path like this, but should be harmless.
path_info = '/'
self.environ = environ
self.path_info = path_info
self.path = '%s/%s' % (script_name.rstrip('/'), path_info.lstrip('/'))
self.META = environ
self.META['PATH_INFO'] = path_info
self.META['SCRIPT_NAME'] = script_name
self.method = environ['REQUEST_METHOD'].upper()
_, content_params = cgi.parse_header(environ.get('CONTENT_TYPE', ''))
if 'charset' in content_params:
try:
codecs.lookup(content_params['charset'])
except LookupError:
pass
else:
self.encoding = content_params['charset']
self._post_parse_error = False
try:
content_length = int(environ.get('CONTENT_LENGTH'))
except (ValueError, TypeError):
content_length = 0
self._stream = LimitedStream(self.environ['wsgi.input'], content_length)
self._read_started = False
self.resolver_match = None
def _get_scheme(self):
return self.environ.get('wsgi.url_scheme')
def _get_request(self):
warnings.warn('`request.REQUEST` is deprecated, use `request.GET` or '
'`request.POST` instead.', RemovedInDjango19Warning, 2)
if not hasattr(self, '_request'):
self._request = datastructures.MergeDict(self.POST, self.GET)
return self._request
@cached_property
def GET(self):
# The WSGI spec says 'QUERY_STRING' may be absent.
raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '')
return http.QueryDict(raw_query_string, encoding=self._encoding)
# ############### 看这里看这里 ###############
def _get_post(self):
if not hasattr(self, '_post'):
self._load_post_and_files()
return self._post
# ############### 看这里看这里 ###############
def _set_post(self, post):
self._post = post
@cached_property
def COOKIES(self):
raw_cookie = get_str_from_wsgi(self.environ, 'HTTP_COOKIE', '')
return http.parse_cookie(raw_cookie)
def _get_files(self):
if not hasattr(self, '_files'):
self._load_post_and_files()
return self._files
# ############### 看这里看这里 ###############
POST = property(_get_post, _set_post)
FILES = property(_get_files)
REQUEST = property(_get_request)
所以,定义属性共有两种方式,分别是【装饰器】和【静态字段】,而【装饰器】方式针对经典类和新式类又有所不同。
类成员的修饰符
类的所有成员在上一步骤中已经做了详细的介绍,对于每一个类的成员而言都有两种形式:
- 共有成员,在任何地方都能访问
- 私有成员,只有在类的内部才能访问
class C:
def __init__(self):
self.name = '共有字段'
self.__foo = '私有字段'
私有成员和共有成员的访问限制不同:
静态字段
- 共有静态字段:类可以访问;类内部可以访问;派生类中可以访问
- 私有静态字段:仅类内部可以访问;(类(对象)._类__字段名 也可访问到)
class C:
name = '公有静态字段'
def func(self):
print(self.name)
class D(C):
def show(self):
print(C.name)
>>> C.name#######
'公有静态字段'
>>> c = C()
>>> c.func()
公有静态字段
>>> d = D()
>>> d.show()
公有静态字段
>>> d.name
'公有静态字段'
>>> d.name
'公有静态字段'
>>> d.func()
公有静态字段
>>>
class C:
__name = '私有静态字段'
def func(self):
print(self.__name)
class D(C):
def show(self):
print(C.__name)
>>> C.__name #类访问 失败
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
C.__name
AttributeError: type object 'C' has no attribute '__name'
>>> c = C()
>>> c.func() #类内部访问 正确
公有静态字段
>>> d = D()
>>> d.func()
公有静态字段
>>> d.show() #派生类中访问 失败
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
d.show()
File "E:/Video/039_private_2.py", line 9, in show
print(C.__name)
AttributeError: type object 'C' has no attribute '_D__name'
>>> C._C__name #类._类__变量名
'公有静态字段'
>>>
普通字段
- 公有普通字段:对象可以访问;类内部可以访问;派生类中可以访问
- 私有普通字段:仅类内部可以访问;
class C:
def __init__(self):
self.foo = '公有字段'
def func(self):
print(self.foo) #类内部访问
class D(C):
def show(self):
print(self.foo) #派生类中访问
>>> c = C()>>> c.foo'公有字段'>>> c.func()公有字段>>> d = D()>>> d.foo'公有字段'>>> d.func()公有字段>>> d.show()公有字段>>>##########
class C:
def __init__(self):
self.__foo = '私有字段'
def func(self):
print(self.__foo)
class D(C):
def show(self):
print(self.__foo)
>>> c = C()>>> c.func()私有字段>>> c.__fooTraceback (most recent call last): File "<pyshell#2>", line 1, in <module> c.__fooAttributeError: 'C' object has no attribute '__foo'>>> d = D()>>> d.show()Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> d.show() File "E:/Video/039_private_4.py", line 11, in show print(self.__foo)AttributeError: 'D' object has no attribute '_D__foo'>>> d.func()私有字段>>> c._C__foo'私有字段'>>> d._C__foo'私有字段'>>>
方法、属性的访问于上述方式类似,即:私有成员只能在类内部使用
ps:非要访问私有属性的话,可以通过 对象._类__属性名
类的特殊成员
上文介绍了Python的类成员以及修饰符,从而了解到类中有字段,方法和属性三大成员,并且成员前有两个下划线,
则表示该成员是私有成员,私有成员只能由类内部调用。无论人或事物往往都有不按套路出牌的情况,Python的类
成员也是如此,存在着一些就有特殊含义的成员,如下:
1、__doc__
表示类的描述信息
class Foo:
"""this is description......"""
def func(self):
pass
>>> print(Foo.__doc__)this is description......>>> Foo.__doc__'this is description......'
2、__module__和__class__
__module__表示当前操作的对象在哪个模块
__class__表示当前操作的对象的类是什么
>>> print(f.__module__)
__main__
>>> print(f.__class__)
<class '__main__.Foo'>
构造方法,通过类创建对象时,自动触发执行。
class Foo:
"""this is description......"""
def __init__(self,name):
self.name = name
self.age = 18
def func(self):
pass
>>> f = Foo('ethan')
>>> f.name
'ethan'
4、__del__
析构方法,当对象在内存中释放时,自动触发执行。
注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作是交给Python
解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。
class Foo1:
def __del__(self):
pass
5、__call__
对象后面加括号,触发执行。
注:构造方法的执行是由创建对象触发的,即:对象 = 类名();而对于__call__方法的执行是由对象后加()触发的,
即:对象() 或者 类()()
class Foo2:
def __init__(self):
pass
def __call__(self,*args,**kwargs):
print('__call__')
>>> f = Foo2() #执行__init__
>>> f() #执行__call__
__call__
>>> Foo2()()
__call__
>>>
6、__dict__
类或对象中所有的成员。
>>> Foo.__dict__
mappingproxy({'__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Foo' objects>, 'func': <function Foo.func at 0x0228D348>, '__init__': <function Foo.__init__ at 0x022538E8>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': 'this is description......'})
上文中我们知道:类的普通字段属于对象;类中的静态字段和方法等属于类,即:
class Province:
country = 'China'
def __init__(self,name,count):
self.name = name
self.count = count
def func(self):
print('func')
获取类的成员,即:静态字段、方法
>>> print(Province.__dict__)
{'__dict__': <attribute '__dict__' of 'Province' objects>, 'func': <function Province.func at 0x0229D4B0>, '__init__': <function Province.__init__ at 0x0229D468>, 'country': 'China', '__module__': '__main__', '__doc__': None, '__weakref__': <attribute '__weakref__' of 'Province' objects>}
获取对象成员
>>> p = Province('hebei',100000)
>>> print(p.__dict__)
{'name': 'hebei', 'count': 100000}
>>>
7、__str__
如果一个类中定义了__str__方法,那么在打印对象的时候,默认输入该方法的返回值。
class Foo3:
def __str__(self):
return '__str__'
>>> s = Foo3()>>> print(s)__str__
8、__getitem__、__setitem__、__delitem__
用于索引操作,如字典。分别表示获取、设置、删除数据
class Foo4(object):
def __getitem__(self,key):
print('__getitem__',key)
def __setitem__(self,key,value):
print('__setitem__',key,value)
def __delitem__(self,key):
print('__delitem__',key)
>>> f = Foo4()
>>> result = f['k1'] #自动触发执行__getitem__
__getitem__ k1
>>> f['k2'] = 'wuli' #自动触发执行 __setitem__
__setitem__ k2 wuli
>>> del f['k1'] #自动触发执行__delitem__
__delitem__ k1
>>>
9、__iter__
用于迭代器
>>> obj = iter([11,21,34,67])
>>> for i in obj:
print(i)
11
21
34
67
>>>
10、__new__、__metaclass__
阅读以下代码:
class Foo6(object):
def __init__(self):
pass
>>> f = Foo6()
上述代码中,f是通过Foo6类实例化的实例化的对象,其实,不仅obj是一个对象,Foo6类本身也是一个对象,
因为在Python中一切事物都是对象。
![Python-31 面向对象:进阶 Python-31 面向对象:进阶](https://image.shishitao.com:8440/aHR0cHM6Ly93d3cuaXRkYWFuLmNvbS9nby9hSFIwY0RvdkwybHRaeTVpYkc5bkxtTnpaRzR1Ym1WMEx6SXdNVGN3T0RFMU1EQXpNVEUyTmprNA%3D%3D.jpg?w=700)