Python:字符串测试未求值



我正在尝试进行简单的字符串比较,但我无法使其工作:

class Bonk:
def __init__(self, thing):
self.thing = thing
def test(self):
if self.thing == 'flarn':
return 'you have flarn'
return 'you have nothing'
bonk1 = Bonk('glurm')
bonk2 = Bonk('flarn')
bonk1.test()
bonk2.test()

这将返回。我也试过这个:

def test(self):
if self.thing in ['flarn']:
...

这也不起作用。

我尝试过双引号,将"flarn"分配给一个变量,然后对该变量进行测试,在列表测试的末尾添加一个逗号。我试着把它作为变量传递。。。但什么都不起作用。

我错过了什么?

您稍微弄错了如何编写OOP类,尽管这是一次很好的尝试,因为您走在了正确的轨道上!

以下是您正在努力实现的目标的工作实现:

class Bonk:
def __init__(self, thing):
self.thing = thing

def test(self):
if (self.thing == 'flarn'):
return 'you have flarn'
return 'you have nothing'
bonk1 = Bonk('glurm')
bonk2 = Bonk('flarn')
print(bonk1.test()) # you have nothing
print(bonk2.test()) # you have flarn

解释

创建Python对象时,__init__是一个自定义函数,它被调用以为对象分配属性。

def __init__(self, thing): # Bonk object constructor with property
self.thing = thing # Set the property for this object

然后,您可以为每个对象创建其他函数,例如test(),它将self作为调用时引用对象本身的第一个参数。

def test(self):
if (self.thing == 'flarn'): # Check the saved property of this object
return 'you have flarn'
return 'you have nothing'

相关文档:https://docs.python.org/3/tutorial/classes.html#class-对象

去掉注释和其他建议的解决方案,您也可以这样做,并通过在初始值设定项中实现函数检查来避免使用另一个函数def-test((。代码行数越少,它就能完成任务。

class Bonk:
def __init__(self, thing):
self.thing = thing
if self.thing == 'flarn':
print('you have flarn')
else:
print('you have nothing')
bonk1 = Bonk('glurm')
bank2 = Bonk('flarn')
=== output ===
you have nothing
you have flarn

最新更新