我已经编程了大约2个月,所以我对Python和编程相对较新。
我有一个包含字符串的字段的类。我试图找到一种方法来表示这个字符串,以便我可以调用它,但我不想让它打印出来。有没有办法让字符串包含打印时不会显示的文字?这就是我暗中所说的。"我知道我可以为此创建一个单独的字段,并且有更复杂的方法来解决这个问题,但我想知道我所描述的简单,简单的过程是否可行。
所以我对此的使用将遵循:
class A(object):
def __init__(self, message):
self.message = message
x = A('\\magical marker\\this is a string.')
y = A("\\other magical marker\\this is a different string")
something = x # I am going to have a variable that could be many different things
if something.message.startswith('\\magical marker\\'):
print something
else:
pass
但是当我打印something
时,我想让它像这样出来:
this is my string
没有神奇的标记。有没有办法做到这一点?
答案 0 :(得分:2)
您打印的something
恰好是A
的一个实例。因此,您可以定义在尝试通过定义魔术方法__str__
来打印对象时会发生什么:
In [1]: class A:
...: def __init__(self, message):
...: self.message = message
...:
...: def __str__(self):
...: return self.message.split('}', 1)[-1]
...:
In [2]: x = A('{marker}my message')
In [3]: print(x)
my message
请注意,打印x.message
将打印整个字符串:
In [4]: x.message
Out[4]: '{marker}my message'
改变这一点会非常混乱。
答案 1 :(得分:2)
如何使用属性重新编程点运算符。
class A(str):
def __init__(self, message):
self.message = message
@property
def message(self):
return 'this is my string'
@message.setter
def message(self, value):
self._message = value
x = A('\\magical marker\\this is a string.')
y = A("\\other magical marker\\this is a different string")
something = x
print x.message
这将始终打印'这是我的字符串'当您尝试访问消息字段时。
答案 2 :(得分:1)
如果你继承自str
,你可以简单地str.replace:
class A(str):
def __init__(self, message):
self.message = message
x = A('\\magical marker\\this is a string.')
y = A("\\other magical marker\\this is a different string")
something = x # I am going to have a variable that could be many different things
if something.message.startswith('\\magical marker\\'):
print something.replace('\\magical marker\\',"",1)
答案 3 :(得分:0)
一个肮脏的小黑客就是使用字符串vs unicode字符串:
x = 'this is a string.'
y = u'this is a unicode string.'
if isinstance(something, str):
print 'str'
else:
print 'unicode'
但这只能让你获得两个不同的课程。也许这就是你所需要的一切?
答案 4 :(得分:0)
其他答案有巧妙的想法,揭示了Python的有趣部分......但是错过了将代码与目标相匹配的标记,以最小的惯用方式。
听起来“标记”是您想要记住的额外状态,并影响以后的决定。
最好的做法是明确:将A
类更改为接受另一个(可能是可选的)初始化参数:
class A(object):
def __init__(self, message, marker=None):
self.message = message
self.marker = marker
然后你直接和明确地检查标记值,没有任何“隐藏”或“解包”:
x = A('this is a string', marker='magic1')
if x.marker == 'magic1':
print x.message
else:
pass
这更好地描述了A
对象的多方面性质 - 即使它们的主要目的是携带字符串message
,它们也有其他重要状态,并且给予该状态一个独特的好处是好的名称和地点。你不必在主消息中“隐藏”它 - 只需给它自己的插槽。
(您甚至可以将确定打印内容/是否打印的条件逻辑移动到A
类的另一个描述性命名方法中 - 使A
的实例对其自己的显示负责 - 规则。)
答案 5 :(得分:0)
你可以使用这样的东西。
class SecretText(str):
def __str__(self):
"""Return empty string."""
return ''
def __repr__(self):
"""Return empty string."""
return self.__str__()
class SomewhatSecretText(str):
def __init__(self, *text):
"""Initialize a SomewhatSecretText instance."""
self.items = list(text)
assert self.verify_types()
# We have to keep some trace. Or we will
# never be able to get the original value.
self.message = ''.join(self.items)
def __str__(self):
"""Return string with hidden text."""
vis = ""
for item in self.items:
vis += str(item)
return vis
def __repr__(self):
"""Return string with hidden text."""
return self.__str__()
def __dir__(self):
"""
This is so self.message and self.items aren't
visible when dir() is called on the instance.
"""
return dir(str)
def verify_types(self):
"""Confirm instance items are strings."""
for item in self.items:
if not isinstance(item, str):
return False
return True
使用SomewhatSecretText
,您可以实现隐藏文字。像这样:
>>> hidden = SecretText("test")
>>> partly_hidden = SomewhatSecretText("This is a ", hidden, "!")
>>> print(partly_hidden)
This is a !
>>> print(repr(partly_hidden))
This is a !
>>> print(str(partly_hidden))
This is a !
您可以使用message
变量获取全文。
>>> print(partly_hidden)
This is a !
>>> print(partly_hidden.message)
This is a test!
奖励是您可以提交任意数量的字符串以进行标记。所以你可以有多个隐藏的部分。