Typing python objects

I am trying to find a way to pass an object reference in python and type in a type similar to Java, but not use it. I duno if this topic exists somewhere here.

My problem is that I need to pass an object reference to the class constructor. But I duno how to give a method a link to an object. In java, although I do this, but I need to pass the code to the server.

Thank you very much 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()
+3
source share
3 answers

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

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

, parent_rectangle SearchRectangle(), , SearchRectangle() .

, , SearchRectangle(), isinstance :

if isinstance(parent_rectangle, SearchRectangle):

: http://dirtsimple.org/2004/12/python-is-not-java.html

+6

python -. ? , , , . , casting, , .

+2

:

Casting / ", , foo, , , , ".

Python has no pointers / links in this sense (although in a different sense, all links). In addition, the compiler / interpreter does not care about what type in the first place. Consequently, casting is impossible and meaningless.

So in your example: just skip the casting type. It will work anyway. And if it is not. then ask a question on this issue.

0
source

Source: https://habr.com/ru/post/1782048/


All Articles