简体   繁体   English

如何在 Python 中动态生成字符串(观察者模式)

[英]How to generate string dynamically in Python (Observer Pattern)

Supposing we have the code below:假设我们有以下代码:

var1="top"
var2=var1+"bottom"

We want to change var1 value if a condition is true:如果条件为真,我们想更改var1值:

if COND==True:
  var1="changed"

Now I want to have var2 dynamically changed .现在我想让var2动态改变 With the code above, var2 will still have the value " topbottom ".使用上面的代码, var2的值仍然是“ topbottom ”。

How can I do that?我怎样才能做到这一点?

Thanks谢谢

You can elegantly achieve this with a callback proxy from ProxyTypes package:您可以使用ProxyTypes包中的回调代理优雅地实现这一点:

>>> from peak.util.proxies import CallbackProxy
>>> var2 = CallbackProxy(lambda: var1+"bottom")
>>> var1 = "top"
>>> var2
'topbottom'
>>> var1 = "left"
>>> var2
'leftbottom'

Each time you access your var2 , callback lambda will be executed and a dynamically generated value returned.每次访问var2 ,都会执行回调 lambda 并返回一个动态生成的值。

You can use string formatting to specify a placeholder in var2 where you want the updated value of var1 to be placed:您可以使用字符串格式在var2中指定一个占位符,您希望在其中放置var1的更新值:

In [1653]: var2 = '{}bottom'

The {} brackets here specify a placeholder.此处的{}括号指定占位符。 Then call var2.format to insert var1 into var2 as and when needed.然后在需要时调用var2.formatvar1插入到var2中。

In [1654]: var1 = 'top'

In [1655]: var2.format(var1)
Out[1655]: 'topbottom'

In [1656]: var1 = 'changed'

In [1657]: var2.format(var1)
Out[1657]: 'changedbottom'

There is no simple way to do this as string are immutable in python.没有简单的方法可以做到这一点,因为字符串在 python 中是不可变的。 There is no way var2 can be changed after var1+"bottom" evaluation.var1+"bottom"评估之后,无法更改var2 You either need to create a new string (not sure why do don't want to do this) or you need to write your own class and create your own objects that accept this behavior.您要么需要创建一个新字符串(不知道为什么不想这样做),要么需要编写自己的类并创建自己的接受此行为的对象。 If you want to do this, take a look at Observer Pattern如果你想这样做,看看观察者模式

As others have said, since strings are immutable you must find a way to insert the dynamic value on the formation of the string.正如其他人所说,由于字符串是不可变的,因此您必须找到一种方法在字符串的形成中插入动态值。

I am a fan of the new 'fstrings' in Python- single line 'if' statement for flare:我是 Python 中新的“fstrings”的粉丝——单行“if”语句用于flare:

cond = True

var1 = "changed" if cond is True else "top"
var2 = f"{var1} bottom"

print(var2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM