使用python转换对象的字符串表示形式

使用python转换对象的字符串表示形式,python,Python,我正在使用字符串PyObject[methodCall=1001,attributeName=javax.servlet.jsp.jstl.fmt.request.charset,attributeValue=UTF-8] 在python中,我有一个类: class PyObject: def __init__(self, methodCall, attributeName, attributeValue): self.methodCall = methodCall self.a

我正在使用字符串
PyObject[methodCall=1001,attributeName=javax.servlet.jsp.jstl.fmt.request.charset,attributeValue=UTF-8]

在python中,我有一个类:

class PyObject:
def __init__(self, methodCall, attributeName, attributeValue):
    self.methodCall = methodCall
    self.attributeName = attributeName
    self.attributeValue = attributeValue
我正在从套接字接收上述字符串,我想将接收到的字符串转换为
PyObject
的对象,以便访问
pyobj.methodCall
等属性


我曾尝试过<代码> JSON.Load()/<代码>,但它给出了我的代码> DICT

,因为您在注释中添加了这个要求是动态的(您也应该把它添加到问题中)考虑这个解决方案。p> 它不是最美丽或最优雅的,但它完成了任务

此解决方案滥用了使用动态创建类和实例的能力

string='PyObject[methodCall=1001,attributeName=javax.servlet.jsp.jstl.fmt.request.charset,attributeValue=UTF-8]'
class_name,string=string.split(“”,maxslit=1)
data=[substring.strip(),用于string.replace('[','')中的子字符串\
.replace(']','').split(','),如果子字符串]
打印(数据)
#['methodCall=1001','attributeName=javax.servlet.jsp.jstl.fmt.request.charset',
#'attributeValue=UTF-8']
数据_dict={}
对于数据中的d:
键,值=d.split('='))
数据dict[键]=值
打印(数据记录)
#{'attributeValue':'UTF-8',
#'attributeName':'javax.servlet.jsp.jstl.fmt.request.charset','methodCall':'1001'}
def初始值(自身,**kwargs):
对于k,v在kwargs.items()中:
setattr(自、k、v)
obj=类型(类名称,(),{'''u_init':init})(**data_dict)
打印(obj)
# 
打印(对象方法调用)
# 1001
打印(对象属性名称)
#javax.servlet.jsp.jstl.fmt.request.charset

您尝试过什么?这对于正则表达式来说很简单。例如,一个非常粗糙的正则表达式应该是
r'methodCall=(?P.*)attributeName=(?P@DeepSpace抱歉,忘记添加了,我已经尝试了
json.loads()
但是它的giving
dict
object输入字符串不是JSON格式。@DeepSpace实际上是由不同的系统处理的输入字符串,所以我不能修改它。regex是唯一的选项吗?
string = 'PyObject [methodCall=1001, attributeName=javax.servlet.jsp.jstl.fmt.request.charset, attributeValue=UTF-8]'

class_name, string = string.split(' ', maxsplit=1)

data = [substring.strip() for substring in string.replace('[', '') \
                                       .replace(']', '').split(',') if substring]

print(data)
# ['methodCall=1001', 'attributeName=javax.servlet.jsp.jstl.fmt.request.charset',
#  'attributeValue=UTF-8']

data_dict = {}
for d in data:
    key, value = d.split('=')
    data_dict[key] = value

print(data_dict)
#  {'attributeValue': 'UTF-8',
#   'attributeName': 'javax.servlet.jsp.jstl.fmt.request.charset', 'methodCall': '1001'}

def init(self, **kwargs):
    for k, v in kwargs.items():
        setattr(self, k, v)

obj = type(class_name, (), {'__init__': init})(**data_dict)
print(obj)
# <__main__.PyObject object at 0x00520C70>
print(obj.methodCall)
# 1001
print(obj.attributeName)
# javax.servlet.jsp.jstl.fmt.request.charset