【发布时间】:2014-04-23 05:49:26
【问题描述】:
你如何创建有效的可重用模块
- 一个模块中的一个类在另一个模块中创建另一个类的实例,并且
- 主程序想要使用仅在其中一个模块的子类中的方法?
在类和子类的上下文中,我的目标是:
- 采用最通用和可重用的类并将它们提取到我可以在多个程序中重用的模块中。
- 在主程序中定义子类,以将代码中最具体(且不可重用)的部分保留在模块之外。
各种类都有自己的逻辑,倾向于在模块内交互并创建彼此的实例——一切都很好。但是当我需要向一个类添加更具体的子类方法时,这些方法对模块内创建的实例不可用。
这是我遇到的一个例子:
==firstclass.py===
"""This is a reusable class within a module. It creates an instance of
another class in another module."""
from secondclass import Shape
class DataObject(object):
"""Create a class that holds data objects."""
def __init__(self, x, y):
self.m_x = x
self.m_y = y
self.m_shape_list = []
def createShape(self, type):
# here we create an instance of the second class
new_shape = Shape(type)
self.m_shape_list.append(new_shape)
def printCoords(self):
print "Coordinates:", (x,y)
===secondclass.py===
"""This is another reusable class. An instance of this gets created within
an another class and it is also subclassed by the main program."""
class Shape(object):
"""Create a class that holds shape info."""
def __init__(self,type):
self.m_type = type
print "Shape:",type
def printShape(self):
print "Shape:",self.m_type
===main.py===
"""This is my main program and where all the classes get subclassed to add
specific implementation details."""
from firstclass import DataObject
from secondclass import Shape
class GraphicObject(DataObject):
"""Create a subclass of DataObject that holds graphic specific info."""
def __init__(self, x, y, color):
print "Init MySubClass"
super(GraphicObject,self).__init__(x, y)
def createSomeShapes(self):
self.createShape('circle')
self.createShape('square')
self.createShape('octogon')
def renderAll(self):
for shape in self.m_shape_list:
shape.render()
class MyShape(Shape):
"""Create a subclass of Shape that holds graphic specific info."""
def __init__(self, type):
if type == circle:
type = 'round thing'
super(MyShape,self).__init__(type)
def render(self):
print "We got a",shape
# Create an instance of the first class
obj = GraphicObject(10, 10, 'yeller')
# Create a few instances of the second class through the interface
# provided by the first class
obj.createSomeShapes()
# Now attempts to call a method of the subclassed second class
obj.renderAll()
当我运行它时,我得到:
$ python main.py
Init MySubClass
Shape: circle
Shape: square
Shape: octogon
Traceback (most recent call last):
File "main.py", line 35, in <module>
obj.renderAll()
File "main.py", line 21, in renderAll
shape.render()
AttributeError: 'Shape' object has no attribute 'render'
我知道为什么会发生这种情况,但我不知道如何优雅地避免它。
这里的最佳做法是什么?如何在允许访问子类方法的同时保持模块代码的可重用性?
【问题讨论】:
标签: python class module subclass modularity