如何将字符串对象的位置更改为对象 [英] How to change string object location to an object

查看:48
本文介绍了如何将字符串对象的位置更改为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符串对象位置转换为对象.我的代码是:

I need to convert string object location to an object. My code is:

class Dog:
    def __init__(self,name):
        self.name= name

    def bark(self):
        print('BAR')

b=''

a=Dog('Test')
print(a)
with open('Dog.txt','w') as file:
   file.write(str(a))

with open('Dog.txt','r') as file:
   b=file.read()
   b=repr(b)

print(b)
b.bark()

我将对象 a 保存在 Dog.txt 文件< __ main__.Dog对象位于0x0000024E1C7AFE80> 上,现在我要使用该字符串并将其转换为对象,以便可以对其使用 bark 方法.

I saved the object a in a Dog.txt file <__main__.Dog object at 0x0000024E1C7AFE80> and now i want to take that string and convert it to an object so I can use the bark method with it.

我该怎么做

推荐答案

,您可以使用 PyYAML :

pip install PYyaml

并从yaml文件中转储和加载数据:

and dump and load data from yaml files:

In [1]: class Dog:
   ...:     def __init__(self,name):
   ...:         self.name= name
   ...: 
   ...:     def bark(self):
   ...:         print('BAR')
   ...: 
   ...: b=''
   ...: 
   ...: a=Dog('Test')
   ...: print(a)
   ...: 
   ...: 
<__main__.Dog object at 0x7fb082811390>

现在将您的对象转储到 yaml :

now dump you object to the yaml:

In [2]: import yaml

In [3]: with open('data.yml', 'w') as outfile:
   ...:     yaml.dump(a, outfile, default_flow_style=False)

data.yml 内,您将看到:

!!python/object:__main__.Dog
name: Test

现在加载:

In [6]: with open('data.yml', 'r') as loadfile:
   ...:     data = yaml.load_all(loadfile)
   ...:     b = next(data)
   ...:     

In [7]: b
Out[7]: <__main__.Dog at 0x7fb07bfd5f28>

In [8]: b.bark()
BAR

这篇关于如何将字符串对象的位置更改为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆