简体   繁体   中英

Is there a “using” in Python?

It's tiring and not concise to call "class.function()" every single time. Is there a way I can just use "function()" to call the function in a class? I'm using Python 3.7.

class SineModel(keras.Model):
    def __init__(self):
        super().__init__()
    ...
    def np_to_tensor(list_of_numpy_objs):
        result = (tf.convert_to_tensor(obj) for obj in list_of_numpy_objs)
        return result
def eval_sine_test(model, optimizer, x, y, x_test, y_test, num_steps=(0, 1, 10)):
    tensor_x_test, tensor_y_test = SineModel.np_to_tensor((x_test, y_test))

You aren't defining the method correctly (nor does there appear to be any reason for it to be a method in the first place). (Well, that's a little harsh. As long as you only call the function via the class, and not an instance, there is little difference between what is technically meant as an instance method and a proper static method).

That said, you barely need to define a specific function for this.

def eval_sine_test(model, optimizer, x, y, x_test, y_test, num_steps=(0, 1, 10)):
    tensor_x_test, tensor_y_test = 
    ...

If you really want a function inside the namespace of the class, define a staticmethod :

class SineModel(keras.Model):
    def __init__(self):
        super().__init__()
    ...

    
    def np_to_tensor(*objs):
        result = (tf.convert_to_tensor(obj) for obj in obj)
        return result
def eval_sine_test(model, optimizer, x, y, x_test, y_test, num_steps=(0, 1, 10)):
    tensor_x_test, tensor_y_test = SineModel.np_to_tensor(x_test, y_test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM