码迷,mamicode.com
首页 > 编程语言 > 详细

python 类

时间:2019-04-19 01:10:45      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:new   HERE   value   sock   count   http   有一个   *args   mod   

class NewClassName: #经典类
class NewClassName(object): #新式类


***********************************************************************

构造函数: #类调用时执行
__init__(self,xx):

***********************************************************************
析构函数: #类释放,销毁时自动执行
__del__(self,xx):
***********************************************************************

私有方法,私有属性: #方法,属性前添加 __

***********************************************************************

##封装


#继承



#多态

 

***********************************************************************

面向对象编程进阶
网址:
www.cnblogs.com/alex3714/articles/5213184.html

 


***********************************************************************
__module__ 和 __class__
  

__module__ 表示当前操作的对象在那个模块

  __class__ 表示当前操作的对象的类是什么


class C:

def __init__(self):
self.name = ‘wupeiqi‘


from lib.aa import C

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


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

 

***********************************************************************
__del__ 析构方法,当对象在内存中被释放时,自动触发执行。


***********************************************************************
__call__ 对象后面加括号,触发执行。

class Foo:

def __init__(self):
pass

def __call__(self, *args, **kwargs):

print ‘__call__‘


obj = Foo() # 执行 __init__
obj() # 执行 __call__


***********************************************************************
__dict__ 查看类或对象中的所有成员  

class Province:

country = ‘China‘

def __init__(self, name, count):
self.name = name
self.count = count

def func(self, *args, **kwargs):
print ‘func‘

# 获取类的成员,即:静态字段、方法、
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‘}


***********************************************************************

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

class Foo:

def __str__(self):
return ‘alex li‘


obj = Foo()
print obj
# 输出:alex li

 

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

class Foo(object):

def __getitem__(self, key):
print(‘__getitem__‘,key)

def __setitem__(self, key, value):
print(‘__setitem__‘,key,value)

def __delitem__(self, key):
print(‘__delitem__‘,key)


obj = Foo()

result = obj[‘k1‘] # 自动触发执行 __getitem__
obj[‘k2‘] = ‘alex‘ # 自动触发执行 __setitem__
del obj[‘k1‘]

***********************************************************************
__new__ \ __metaclass__

class Foo(object):


def __init__(self,name):
self.name = name


f = Foo("alex")

上述代码中,obj 是通过 Foo 类实例化的对象,其实,不仅 obj 是一个对象,Foo类本身也是一个对象,因为在Python中一切事物都是对象。

如果按照一切事物都是对象的理论:obj对象是通过执行Foo类的构造方法创建,那么Foo类对象应该也是通过执行某个类的 构造方法 创建。


print type(f) # 输出:<class ‘__main__.Foo‘> 表示,obj 对象由Foo类创建
print type(Foo) # 输出:<type ‘type‘> 表示,Foo类对象由 type 类创建

所以,f对象是Foo类的一个实例,Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建。
a). 普通方式

class Foo(object):

def func(self):
print ‘hello alex‘


b). 特殊方式

 

def func(self):
print ‘hello wupeiqi‘

Foo = type(‘Foo‘,(object,), {‘func‘: func})
#type第一个参数:类名
#type第二个参数:当前类的基类
#type第三个参数:类的成员

 


So ,孩子记住,类 是由 type 类实例化产生

类中有一个属性 __metaclass__,其用来表示该类由 谁 来实例化创建,所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看 类 创建的过程。

class MyType(type):
def __init__(self,*args,**kwargs):

print("Mytype __init__",*args,**kwargs)

def __call__(self, *args, **kwargs):
print("Mytype __call__", *args, **kwargs)
obj = self.__new__(self)
print("obj ",obj,*args, **kwargs)
print(self)
self.__init__(obj,*args, **kwargs)
return obj

def __new__(cls, *args, **kwargs):
print("Mytype __new__",*args,**kwargs)
return type.__new__(cls, *args, **kwargs)

print(‘here...‘)
class Foo(object,metaclass=MyType):


def __init__(self,name):
self.name = name

print("Foo __init__")

def __new__(cls, *args, **kwargs):
print("Foo __new__",cls, *args, **kwargs)
return object.__new__(cls)

f = Foo("Alex")
print("f",f)
print("fname",f.name)


***********************************************************************


反射
通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法

def getattr(object, name, default=None): # known special case of getattr
"""
getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, ‘y‘) is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn‘t
exist; without it, an exception is raised in that case.
"""
pass


判断object中有没有一个name字符串对应的方法或属性

def setattr(x, y, v): # real signature unknown; restored from __doc__
"""
Sets the named attribute on the given object to the specified value.

setattr(x, ‘y‘, v) is equivalent to ``x.y = v‘‘


def delattr(x, y): # real signature unknown; restored from __doc__
"""
Deletes the named attribute from the given object.

delattr(x, ‘y‘) is equivalent to ``del x.y‘‘
"""


实例
class Foo(object):

def __init__(self):
self.name = ‘wupeiqi‘

def func(self):
return ‘func‘

obj = Foo()

# #### 检查是否含有成员 ####
hasattr(obj, ‘name‘)
hasattr(obj, ‘func‘)

# #### 获取成员 ####
getattr(obj, ‘name‘)
getattr(obj, ‘func‘)

# #### 设置成员 ####
setattr(obj, ‘age‘, 18)
setattr(obj, ‘show‘, lambda num: num + 1)

# #### 删除成员 ####
delattr(obj, ‘name‘)
delattr(obj, ‘func‘)

*******************************************************************
异常处理
参考 http://www.cnblogs.com/wupeiqi/articles/5017742.html


try:
open(‘test.py‘)
except Exception as e:
print(‘出错了:‘,e)

 


演示raise用法
try:
s = None
if s is None:
print "s 是空对象"
raise NameError #如果引发NameError异常,后面的代码将不能执行
print len(s) #这句不会执行,但是后面的except还是会走到
except TypeError:
print "空对象没有长度"

s = None
if s is None:
raise NameError
print ‘is here?‘ #如果不使用try......except这种形式,那么直接抛出异常,不会执行到这里

socket编程
http://www.cnblogs.com/wupeiqi/articles/5040823.html

 

python 类

标签:new   HERE   value   sock   count   http   有一个   *args   mod   

原文地址:https://www.cnblogs.com/jasonLiu2018/p/10733388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!