在 python 开发中 我定义了很多验证器 当我字段单独验证的的时候 类名需要根据 "字段名+ From "动态实例化,我按照 PHP 的办法弄了半天没有什么效果。后面自己写了两个 demo 查了下资料。已解决
php demo
<?php
//当我们直接new一个未包含class类文件时候会报错
class test1
{
function a(){
die('this is a');
}
}
class test2
{
function b(){
die('this is b');
}
}
$arr = ['test1'=>'a','test2'=>'b'];
$r = array_rand($arr);
$c = new $r;
print_r($c->$arr[$r]());
?>
python demo
import random
class test1(object):
def a(self):
print('this is test a')
class test2(object):
def b(self):
print('this is test b')
d = {'test1':'a','test2':'b'}
res = random.choice(list(d.keys()))
f = d.get(res)
# 这里和PHP不一样的是需要字符编译成对象
o_name = res + "()"
o = eval(o_name)
o_f = getattr(o,f)()
print(o_f)
T Y F 1年前
走过路过不要错过🙆🏼