Heartbeat
Heartbeat

Reputation: 59

Use case of python function argument

I have a python function named grids() with keyword self in arguments, and another python function named build_targets(). I want to use gridsize and anchor_vec from grids() to another python function named build_targets(). Both functions are following:

def grids(self, img_size=(608,608), gridsize=(19, 19), device='cpu', type=torch.float32):

    nx, ny = gridsize  # x and y grid size
    self.nx = nx
    self.ny = ny

    if isinstance(img_size, int):
        self.img_size = int(img_size)
    else:
        self.img_size = max(img_size)

    self.stride = self.img_size / max(gridsize)

    yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])

    self.register_buffer('grid_xy', torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).to(device)) 


    self.anchor_vec = self.anchors.to(device) / self.stride
    self.register_buffer('gridsize',torch.Tensor(gridsize).to(device))


def build_targets(model, targets):

    for i in layers_list:
        ng, anchor_vec = gridsize, anchor_vec # from grids() 

Is there any way to use gridsize and anchor_vec in build_targets() or how do I call it in build_target() function?

Any comments would be highly appreciated!

Upvotes: 0

Views: 96

Answers (1)

AcaNg
AcaNg

Reputation: 706

It seems like grids() is a method inside a class, then you have 2 choices:

  1. Modify build_targets(), make it a method inside a class by adding self to its arguments:
class SomeClass:
    def grids(...):
        self.gridsize = gridsize # (*)
        #some code

    def build_targets(self, model, targets):
        for i in layers_list:
            ng, anchor_vec = self.gridsize, self.anchor_vec # requires (*)
            # or
            ng, anchor_vec = (self.nx, self.ny), self.anchor_vec # does not requires (*)

Calling:

some_instance.build_targets(some_model, some_targets)
  1. Add more arguments to build_targets():
def build_targets(model, targets, gridsize, anchor_vec):
    for i in layers_list:
        ng, anchor_vec = gridsize, anchor_vec

Calling:

build_targets(some_model, some_targets, (some_instance.nx, some_instance.ny), some_instance.anchor_vec)
# quite long line

By this way, build_targets() is "independent" to the class. Doing this is equivalent to moving build_targets() out of the class.

Upvotes: 1

Related Questions