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?