我一直在尝试搜索如何在python中传递对象引用并键入类似于Java的类型,但没有用.我duno如果这个话题存在于某处.
我的麻烦是我必须将对象引用传递给类构造函数.但我duno如何对一个对象的引用进行类型转换.在java虽然我已经完成了这个,但我必须将代码传输到服务器端.
非常感谢,杰克
class SearchRectangle:
def __init__(self, lower_left_subgrid_x, lower_left_subgrid_y, rectangle_width, rectangle_height):
self.min_subgrid_x = int(lower_left_subgrid_x)
self.max_subgrid_x = int(self.min_subgrid_x + rectangle_width -1)
self.min_subgrid_y = int(lower_left_subgrid_y)
self.max_subgrid_y = int(self.min_subgrid_y + rectangle_height -1)
...blah
class SearchRectangleMultiGrid:
# parent rectangle should be a SearchRectangle instance
def __init__(self, parent_rectangle):
self.parent_rectangle = SearchRectangle()parent_rectangle
# test codes
test_rect = SearchRectangle(test_subgrid.subgrid_x, test_subgrid.subgrid_y, 18, 18)
print "\n\nTest SearchRectangle";
print test_rect.to_string()
print test_rect.sql_clause
test_rec_multi = SearchRectangleMultiGrid(test_rect)
print "\n\nTest SearchRectangleMulti"
test_rec_multi.parent_rectangle.to_string()
Run Code Online (Sandbox Code Playgroud)
Python是一种动态类型语言,因此除非你特别需要它,否则构建一些东西没有多大意义.
在Python中,你应该使用Duck Typing:http://en.wikipedia.org/wiki/Duck_typing
因此,您应该只测试是否具有您需要的属性,而不是尝试转换parent_rectangle为a .SearchRectangle()SearchRectangle()
或者,如果你真的想确定你总是得到一个SearchRectangle(),请使用isinstance如下:
if isinstance(parent_rectangle, SearchRectangle):
Run Code Online (Sandbox Code Playgroud)
这可能是一个很好的阅读:http://dirtsimple.org/2004/12/python-is-not-java.html