Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: string test not evaluating

I’m trying to do what should be simple string comparison, but I can’t get it to work:

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()

This returns nothing. I’ve tried this too:

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

and that doesn’t work either.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried double quotes, assigning ‘flarn’ to a variable and then testing against the variable, adding a comma at the end of the list test. I tried passing it in as a variable instead… but nothing is working.

What am I missing?

>Solution :

You have mistaken how to write OOP classes slightly, though a good attempt since you are on the right track!

Here is a working implementation of what you’re trying to achieve:

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

Explanation

When creating a Python Object, the __init__ is a customization function that is called in order to assign properties to the object.

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

You can then create additional functions for each object, such as test(), which takes self as the first parameter that will reference the object itself when invoked.

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

Relevant Documentation: https://docs.python.org/3/tutorial/classes.html#class-objects

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading