Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python object typecasting

Tags:

python

Ive been trying search how to pass object reference in python and type cast it similar to Java but no to avail. I duno if this topic exists somewhere here.

My trouble is i have to pass the object reference to a class constructor. But i duno how to typecast the reference to an object. In java though I have accomplish this but i have to transfer the code to the server side.

many thanks, Jack

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()
like image 995
Jack Wong Avatar asked Jun 15 '26 14:06

Jack Wong


2 Answers

Python is a dynamically typed language and as such, it doesn't make much sense to cast something unless you specifically need it in that type.

In Python you should use Duck Typing instead: http://en.wikipedia.org/wiki/Duck_typing

So instead of trying to convert parent_rectangle to a SearchRectangle() you should simply test if SearchRectangle() has the properties you need.

Or if you really want to be sure that you'll always get a SearchRectangle(), use isinstance like this:

if isinstance(parent_rectangle, SearchRectangle):

This might be a good read for you: http://dirtsimple.org/2004/12/python-is-not-java.html

like image 176
Wolph Avatar answered Jun 17 '26 05:06

Wolph


There's no reason to cast anything in python. What are you trying to do? Just use the object like you would, and if it's not of the correct type it will fail. There's no such thing as casting since variable names don't have a type associated with them.

like image 28
Falmarri Avatar answered Jun 17 '26 06:06

Falmarri