在OOP程序设计中,当我们定义一个class的时候,可以从某个现有的class继承,新的class称为子类(Subclass),而被继承的class称为基类、父类或超类(Base class、Superclass)。
>>> class Animal(object):#名为Animal的class
defrun(self):
print'Animal is running...'
>>> class Dog(Animal):#从Animal类继承
pass
>>> dog=Dog()
>>> dog.run()#子类获得了父类的全部功能
Animal is running...
>>> class Dog(Animal):#对子类增加一些方法
defrun(self):
print'Dog is running...'
>>> dog=Dog()
>>> dog.run()
Dog is running...
多态
a = List() # a是List类型
b = Animal() # b是Animal类型
c = Dog() # c是Dog类型
>>> isinstance(a,List)
True
在继承关系中,如果一个实例的数据类型是某个子类,那它的数据类型也可以被看做是父类。但是,反过来就不行:
>>> b = Animal()
>>> isinstance(b,Dog)
False
继承可以把父类的所有功能都直接拿过来,这样就不必重零做起,子类只需要新增自己特有的方法,也可以把父类不适合的方法覆盖重写;有了继承,才能有多态。在调用类实例方法的时候,尽量把变量视作父类类型,这样,所有子类类型都可以正常被接收;
使用type()判断对象类型,使用type()函数:
使用isinstance()>>> type(123)#基本类型都可以用type()判断
<type 'int'>
>>> type('str')
<type 'str'>
>>> type(None)
<type 'nonetype'>
>>> type(abs)#变量指向函数或者类,也可以用type()判断
<type 'builtin_function_or_method'>
>>> type(a)
<class '__main__.Animal'>
>>> type(123)==type(456)#比较两个变量的type类型是否相同
True
>>> import types#Python把每种type类型都定义好了常量,放在types模块里
>>> type('abc')==types.StringType
True
>>> type(u'abc')==types.UnicodeType
True
>>> type([])==types.ListType
True
>>> type(str)==types.TypeType
True
>>> type(int)==type(str)==types.TypeType#特殊的类型
True
isinstance()可以告诉我们,一个对象是否是某种类型。他判断的是一个对象是否是该类型本身,或者位于该类型的父继承链上。
使用dir()>>> isinstance(d,Dog) and isinstance(d,Animal)
True
>>> isinstance('a',str)
True#能用type()判断的基本类型也可以用isinstance()判断
>>> isinstance('a',(str,unicode))
True# 判断一个变量是否是某些类型中的一种
>>> isinstance(u'a',basestring)
True#str和unicode都是从basestring继承下来的
>>> dir('ABC')#获得一个str对象的所有属性和方法
['__add__','__class__','__contains__','__delattr__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__getnewargs__','__getslice__','__gt__','__hash__','__init__','__le__','__len__','__lt__','__mod__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__rmod__','__rmul__','__setattr__','__sizeof__','__str__','__subclasshook__','_formatter_fIEld_name_split','_formatter_parser','cAPItalize','center','count','decode','encode','endswith','expandtabs','find','format','index','isalnum','isAlpha','isdigit','islower','isspace','isTitle','isupper','join','ljust','lower','lstrip','partition','replace','rfind','rindex','rjust','rpartition','rsplit','rstrip','split','splitlines','startswith','strip','swapcase','Title','translate','upper','zfill']
类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:
>>> len('ABC')
3
>>> 'ABC'.__len__()
3
我们自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法:
>>> class MyObject(object):
def__len__(self):
return 100
>>> obj = MyObject()
>>> len(obj)
100
配合getattr()、setattr()以及hasattr(),我们可以直接 *** 作一个对象的状态:
class MyObject(object):
def__init__(self):
self.x = 9
defpower(self):
return self.x * self.x
>>> hasattr(obj,'x') # 有属性'x'吗?
True
>>> obj.x
9
>>> hasattr(obj,'y') # 有属性'y'吗?
False
>>> setattr(obj,'y',19) # 设置一个属性'y'
>>> hasattr(obj,'y') # 有属性'y'吗?
True
>>> getattr(obj,'y') # 获取属性'y'
19
>>> obj.y # 获取属性'y'
19
>>> getattr(obj,'z',404) # 获取属性'z',如果不存在,返回默认值404
404
>>> hasattr(obj,'power') # 有属性'power'吗?
True
>>> getattr(obj,'power') # 获取属性'power'
<bound method MyObject.power of<__main__.MyObject object at 0x108ca35d0>>
>>> fn = getattr(obj,'power') # 获取属性'power'并赋值到变量fn
>>> fn # fn指向obj.power
<bound method MyObject.power of<__main__.MyObject object at 0x108ca35d0>>
>>> fn() # 调用fn()与调用obj.power()是一样的
81
使用__slots__>>> class Student(object):
pass
>>> s = Student()
>>> s.name = 'Michael' # 动态给实例绑定一个属性
>>> print s.name
Michael
>>> def set_age(self,age): # 定义一个函数作为实例方法
self.age = age
>>> from types import MethodType
>>> s.set_age = MethodType(set_age,s,Student) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结果
25
但是,给一个实例绑定的方法,对另一个实例是不起作用的:
>>> s2 = Student() # 创建新的实例
>>> s2.set_age(25) # 尝试调用方法
Traceback (most recent call last):
file"<stdin>",line 1,in <module>
AttributeError: 'Student' object has no attribute'set_age'
为了给所有实例都绑定方法,可以给class绑定方法:
>>> def set_score(self,score):
... self.score = score
...
>>> Student.set_score = MethodType(set_score,None,Student)
给class绑定方法后,所有实例均可调用:
>>> s.set_score(100)
>>> s.score
100
>>> s2.set_score(99)
>>> s2.score
99
为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class能添加的属性:
>>> class Student(object):
__slots__ = ('name','age') # 用tuple定义允许绑定的属性名称
>>> s = Student() # 创建新的实例
>>> s.name = 'Michael' # 绑定属性'name'
>>> s.age = 25 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
file"<stdin>",in <module>
AttributeError: 'Student' object has no attribute'score'
由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。
使用__slots__要注意,__slots__定义的属性仅对当前类起作用,对继承的子类是不起作用的:
>>> class GraduateStudent(Student):
... pass
...
>>> g = GraduateStudent()
>>> g.score = 9999
除非在子类中也定义__slots__,这样,子类允许定义的属性就是自身的__slots__加上父类的__slots__。
总结以上是内存溢出为你收集整理的Python学习 Day 8 继承 多态 Type isinstance dir __slots__全部内容,希望文章能够帮你解决Python学习 Day 8 继承 多态 Type isinstance dir __slots__所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)