0

I am trying to build a program in an object oriented fashion. My Phrase object can contain one or more Noun objects. When you cast the Phrase to string, join the nouns list together like this

@property
def nouns_text(self) -> str:
    return ' '.join(self.nouns)

But this raises the error

Traceback (most recent call last):
  File "jovin.py", line 173, in <module>
    print(subject)
  File "jovin.py", line 131, in __str__
    return str(self.phrase)
  File "jovin.py", line 82, in __str__
    return str(self.text)
  File "jovin.py", line 78, in text
    text:str = f'{self.adverbs_text} {self.adjectives_text} {self.nouns_text}'
  File "jovin.py", line 74, in nouns_text
    return ' '.join(self.nouns)
TypeError: sequence item 0: expected str instance, Pronoun found

It appears that join will only work with objects that ARE strings, not objects that behave like strings.

I can solve this problem by doing this

' '.join([str(x) for x in self.nouns])

or by creating a staticmethod to do it

@staticmethod
def convert_list_to_text(self, part_of_speech):
    return ' '.join([str(x) for x in part_of_speech])

@property
def adverbs_text(self) -> str:
    return self.convert_list_to_text(self.adverbs)

@property
def nouns_text(self) -> str:
    return self.convert_list_to_text(self.nouns)

But it feels like a hack either way.

Can someone either explain another way to do this, or why this is the right way to go?

  • What is the definition of `Noun`? If it behaves like a string, it should have the [__str__ and __repr__ method](https://stackoverflow.com/q/1436703/13253010). – thedemons Nov 11 '22 at 23:25
  • It does have __str__ and __repr__ methods. (The representation of the object is __str__) – jordynfinity Nov 11 '22 at 23:30

1 Answers1

0
' '.join([str(x) for x in self.nouns])

This is good, and it's what you should do. There's one slight optimization you can do. Rather than constructing an intermediate list, you can use a generator expression.

' '.join(str(x) for x in self.nouns)

Or, if you prefer map calls,

' '.join(map(str, self.nouns))

Either is acceptable and they're basically equivalent.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116