1. 例一 类是一种类型,内建类型(int,float)也是一种类
class Myclass(): pass print(type(Myclass)) print(type(Myclass())) print(type(0)) print(type(int))
结果
<class 'type'> <class '__main__.Myclass'> <class 'int'> <class 'type'>
所以,3.0中统一了,类是类型,int是一种类型,类型也是一种类型。
例二:一切皆对象
def fn(self,name='world'): print('Hello,%s.'% name) Hello = type('Hello',(object,),dict(hello=fn)) #函数能够被赋值 h=Hello() h.hello() #Hello,world.
以上,函数是对象
class ObjectCreator(): pass print(ObjectCreator) def echo(o): print(o) echo(ObjectCreator) #可以将它作为参数传给函数 ObjectCreator.newattr = 'foo' print(hasattr(ObjectCreator,'newattr')) ObjectCreator2=ObjectCreator #你可将它赋给一个变量 print(ObjectCreator2())
运行结果:
<class '__main__.ObjectCreator'>
<class '__main__.ObjectCreator'>
True
<__main__.ObjectCreator object at 0x0027B430>
以上,类也是对象
例三:关于“self”
首先,方法是类属性,不是实例属性。类中的方法有self,self表示用于在类实例方法中引用方法所绑定的实例。因为方法的实例在任何方法调用中总是第一个参数传递的,self被选中来代表实例。
class C(): def test(self): print('got it') c=C()
print(C.test) #类属性,表示一种函数 print(c.test) #C.test的绑定方法,方法只有实例才能被调用 c.test() C.test(c) #这样行!!!
显示结果
<function C.test at 0x006F36F0> <bound method C.test of <__main__.C object at 0x001FB490>> got it got it
下面的代码也可以行
class C(): def test(self): print('got it') class P(C): def test(self): print('got it 2') pass p=P() C.test(p) #got it p.test() #got it 2
例四:__new__和__init__区别
在实例创建过程中__new__方法先于__init__方法被调用,因为所有的__new__方法是类方法,所以传入类的第一个参数是类,一般用cls表示。
如果不需要其它特殊的处理,可以使用object的__new__方法来得到创建的实例(也即self)。
于是我们可以发现,实际上可以使用其它类的__new__方法类得到这个实例,只要那个类或其父类或祖先有__new__方法。
class another(object):
def __new__(cls,*args,**kwargs):
print("newano")
return object.__new__(cls, *args, **kwargs)
class display(object):
def __init__(self, *args, **kwargs):
print("init")
def __new__(cls, *args, **kwargs):
print("newdis")
print(type(cls))
return another.__new__(cls, *args, **kwargs)
a=display()
运行结果
newdis
<class 'type'>
newano
init
例子五:对标准类型子类化
1 a=dict((('wangzixuan',12),('wangzifeng',13),('lingmiaoqiang',14))) 2 print(sorted(a.keys())) 3 4 class SortedKeyDict(dict): 5 def keys(self): 6 return sorted(super(SortedKeyDict,self).keys()) #这句话必须用super(SortedKeyDict,self),如果用self会 报错 7 a=SortedKeyDict((('wangzixuan',12),('wangzifeng',13),('lingmiaoqiang',14))) print(a.keys())
运行结果
['lingmiaoqiang', 'wangzifeng', 'wangzixuan'] ['lingmiaoqiang', 'wangzifeng', 'wangzixuan']
解释:当创建实例的时候,因为我们调用的类是dict的基类,除了self()其他内置函数没有改变,所以第七行等同于第一行。
因为dict类(是的,dict是一种类)中,实例a采用a.keys()有提取字典的keys的作用,所以我们可以重新定义keys()函数,使得可以提取字典的keys并进行排序,所以要调用dict类中的方法,参见第6行。
如果我们不重新定义keys()函数,那SortedKeyDict()要调用keys()时会引用子类dict中的keys。
class SortedKeyDict(dict): pass a=SortedKeyDict((('wangzixuan',12),('wangzifeng',13),('lingmiaoqiang',14))) print(a.keys()) print(sorted(a.keys()))
显示结果
dict_keys(['wangzixuan', 'wangzifeng', 'lingmiaoqiang'])
['lingmiaoqiang', 'wangzifeng', 'wangzixuan']
例子六 __存储机制
1 from time import time ,ctime 2 class P(): 3 def __init__(self): 4 self.__ctime =3 5 6 class TimeWrap(P): 7 8 def __init__(self,obj): 9 self.__data = obj 10 self.__ctime = time() 11 super(TimeWrap,self).__init__() 12 13 def gettimeval(self): 14 return getattr(self,'_%s__ctime' % self.__class__.__name__) 15 16 def __str__(self): 17 return ctime(self.__ctime) 18 19 print(TimeWrap.__dict__) 20 a = TimeWrap('1') 21 print(a.__dict__) 22 print(a._TimeWrap__data) 23 print(a.gettimeval()) 24 print(ctime(a.gettimeval())) #ctime是将浮点格式保存的时间转换成字符串形式的函数 25 print(a)
输出结果:
{'__module__': '__main__', '__init__': <function TimeWrap.__init__ at 0x01E13B28>, 'gettimeval': <function TimeWrap.gettimeval at 0x01E13AE0>, '__str__': <function TimeWrap.__str__ at 0x01E13A98>, '__doc__': None}
{'_TimeWrap__data': '1', '_TimeWrap__ctime': 1484439307.372132, '_P__ctime': 3}
1
1484439307.372132
Sun Jan 15 08:15:07 2017
Sun Jan 15 08:15:07 2017
虽然程序中有基类和父类有两个__ctime属性,但是它们的存储机制,不会让子类被覆盖。
__开头的属性和方法在存储中会_类名__(属性/方法)存储