I am quite new to OOP in Python.
To avoid duplicate code in methods of a class I want to introduce a function within a class which is then called from the methods. From logical point of view these function should belong to the class and should not be a global function.
I have attached a small (nonsense) example. But the example only runs when the function "SillyName" is placed outside of the class as global function. But it should be part of the class. I am not sure how to do that, because when I place it inside, I am getting an error (NameError: name 'SillyName' is not defined). Can you help?
import random
class SillyPerson:
def __init__(self, FirstName, LastName):
self.FirstName = SillyName(FirstName)
self.LastName = SillyName(LastName)
def __str__(self):
return (f"Name is {self.FirstName} {self.LastName}")
def SillyName (name):
""" returns a silly name if a None-Monthy-Python-Name is passed"""
if name in "John Cleese Eric Idle Michael Palin Terry":
return name
else:
return ''.join(random.sample(name,len(name)))
person1 = SillyPerson ("Michael","Moore")
person2 = SillyPerson ("Silvester","Stalone")
print (person1)
print (person2)