python - 如何动态获取某个对象的某个属性的名字
天蓬老师
天蓬老师 2017-04-18 10:17:21
0
2
726

举个例子

class A:
    def __init__(self,value1,value2):
        self.value1=value1
        self.value2=value2

def function(value):
    #do some thing and get the name of obj.property
    print(property)

tempObj=A()    

function(tempObj.value1)#这里会print输出value1,无论value1值是多少
function(tempObj.value2)#这里会print输出value2,无论value2值是多少

真实遇到的问题是这样的
在写restfulApi,每次会在逻辑代码前要检查传入数据的正确性,经常会检查数组的长度

然后大概写成这样

def post(self):
    parsed_data = self.parser.parse_args()
    if len(parsed_data.T) < 8:
        return make_parser_error('T', '不得少于8个')

我想把代码变成

def post(self):
    parsed_data = self.parser.parse_args()
    check_result=function(parsed_data.T,8)
    if check_result:
        return check_result,400 #400是返回状态码
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
阿神

It should not be possible to obtain variable names through variables in Python. At most, the class name can be obtained, because Python is a value type. If value1 and value2 have the same value, then they are exactly the same objects and point to the same place in the memory

伊谢尔伦

python3

__dict__

class A:
    def __init__(self,v=0):
        self.v=v

        
a=A()
print(a.v) # 0

for k,v in a.__dict__.items():
    print('key:%s, val:%d' % (k,v))

    
# key:v, val:0
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!