《python 从入门到精通》§7 更多抽象:对象
时间:2009-08-18 来源:oychw
§7 更多抽象:对象
§7.1 对象的作用
多态、封装、继承
多态:
# Don't do it like this...
def getPrice(object):
if isinstance(object, tuple):
return object[1]
else:
return magic_network_method(object)
§7.2 类及类型
__metaclass__ = type # Make sure we get new style classes
class Person:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
print "Hello, world! I'm %s." % self.nam
__metaclass__ = type表示使用新的类。使其作为一个新类的子类也可以做到这点。
>>> class Class:
def method(self):
print 'I have a self!'
>>> def function():
print "I don't..."
>>> instance = Class()
>>> instance.method()
I have a self!
>>> instance.method = function
>>> instance.method()
I don't...
python间接支持private,如下的__inaccessible即为私有的。
class Secretive:
def __inaccessible(self):
print "Bet you can't see me..."
def accessible(self):
print "The secret message is:"
self.__inaccessible()
但是依然可以这样访问:
>>> s._Secretive__inaccessible()
Bet you can't see me...
import * 不会导入下划线开头的方法。
指定父类:
class Filter:
def init(self):
self.blocked = []
def filter(self, sequence):
return [x for x in sequence if x not in self.blocked]
class SPAMFilter(Filter): # SPAMFilter is a subclass of Filter
def init(self): # Overrides init method from Filter superclass
self.blocked = ['SPAM']
>>> s = SPAMFilter()
>>> s.init()
>>> s.filter(['SPAM', 'SPAM', 'SPAM', 'SPAM', 'eggs', 'bacon', 'SPAM'])
['eggs', 'bacon']
>>> issubclass(SPAMFilter, Filter)
True
>>> SPAMFilter.__bases__
(<class __main__.Filter at 0x171e40>,)
>>> Filter.__bases__
()
>>> s = SPAMFilter()
>>> isinstance(s, SPAMFilter)
True
>>> isinstance(s, Filter)
True
>>> isinstance(s, str)
False
isinstance往往不如多态可靠。
多继承:
class Calculator:
def calculate(self, expression):
self.value = eval(expression)
class Talker:
def talk(self):
print 'Hi, my value is', self.value
class TalkingCalculator(Calculator, Talker):
pass
如果方法相同,前面一个父类重载后面父类的。
检查属性是否存在
>>> hasattr(tc, 'talk')
True
>>> hasattr(tc, 'fnord')
False
检查函数是否可以调用:
>>> callable(getattr(tc, 'talk', None))
True
callable在3.0要使用:hasattr(x, '__call__').
修改属性:
>>> setattr(tc, 'name', 'Mr. Gumby')
>>> tc.name
'Mr. Gumby
查看一个对象中的所有属性:__dict__。inspect模块可以查看一个对象的组成。
§7.3 面向对象设计
略