天天看点

python表明变量和函数返回值类型的方式

在C++中,形参和函数返回值都必须声明类型,一是语法要求,二也更容易debug时了解变量和返回值的类型。

python不需要显式指定,但是为了看起来方便,也可以加上类型说明。

以一个例子来说:

class SaveOnBestTrainingRewardCallback(BaseCallback):
    """
    callbacks for saving a model (the check is done every '''check_freq''' steps)
    based on the training reward(in practioe,we recommend using 'evalCallback')

    :param check_freq:(int)
    """

    def __init__(self,check_freq:int,log_dir:str,verbose=1):
        super(SaveOnBestTrainingRewardCallback,self).__init__(verbose)
        self.check_freq=check_freq
        self.log_dir=log_dir
        self.save_path=os.path.join(log_dir,'best_model')
        self.best_mean_reward=-np.inf

    def _init_callback(self) -> None:
        if self.save_path is not None:
            os.makedirs(self.save_path,exist_ok=True)

    def _on_step(self) -> bool:
        if self.n_calls % self.check_freq==0:
            x,y=ts2xy(load_results(self.log_dir),'timesteps')
            if len(x)>0:
                mean_reward=np.mean(y[-100:])
                if self.verbose>0:
                    print('num timesteps:{}'.format(self.num_timesteps))
                    print('best mean reward:{:.2f} - Last mean reward per episode:{:.2f}'.format(self.best_mean_reward,mean_reward))

                if mean_reward>self.best_mean_reward:
                    self.best_mean_reward=mean_reward
                    if self.verbose>0:
                        print('saving new best model to {}'.format(self.save_path))
                    self.model.save(self.save_path)
        return True
           

在这个类中,__init__函数的形参用

check_freq:int

这样的形式来说明。

def _on_step(self) -> bool

这样的形式来说明返回值的类型。

这些有或没有不影响程序的运行。