擅长:python、mysql、java
<p>如果你想特别地比较字符串,你可以用两种不同的方法。首先是定义类的<code>__str__</code>方法:</p>
<pre><code>class Hello:
def __init__(self, data="HelloWorld"):
self._data = data
def __str__(self):
return self._data
</code></pre>
<p>然后可以将字符串与以下项进行比较:</p>
<pre><code>h = Hello()
str(h) == "HelloWorld"
</code></pre>
<p>或者您可以特别使用<code>__eq__</code>特殊函数:</p>
<pre><code>class Hello:
def __init__(self, data="HelloWorld"):
self._data = data
def __str__(self):
return self._data
def __eq__(self, other):
if isinstance(other, str):
return self._data == other
else:
# do some other kind of comparison
</code></pre>
<p>然后您可以执行以下操作:</p>
<pre><code>h = Hello()
h == "HelloWorld"
</code></pre>