0

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)
Nisse
  • 43
  • 7
  • Consider a private method (with `_` prefix) – jorzel Dec 22 '21 at 17:53
  • 2
    I dont understand what you don't understand... you already defined *two function* inside your class, what is it about the third function that is not working? – juanpa.arrivillaga Dec 22 '21 at 17:54
  • ", because when I place it inside, I am getting an error." **what error?** Please, don't ever just say "I am getting an error". Telll us *what you did exactly and what error you got, exactly, including the full error message with the stack trace". – juanpa.arrivillaga Dec 22 '21 at 17:55
  • 2
    Possible duplicate of [Meaning of classmethod and staticmethod for beginner?](https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner) – jpp Dec 22 '21 at 17:59

3 Answers3

0

Methods inside a class need to have self as argument when getting written and a leading self. when getting called.

import random

class SillyPerson:
    def __init__(self, FirstName, LastName):
        self.FirstName  = self.SillyName(FirstName)
        self.LastName   = self.SillyName(LastName)

    def __str__(self):
        return (f"Name is {self.FirstName} {self.LastName}")


    def SillyName (self, 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)

Ravi Prakash
  • 136
  • 4
  • 1
    well, now there is no need for it to be an instance method (it could be a `@staticmethod` and the argument `self` could be removed because it is not used even tho it is a method) – Matiiss Dec 22 '21 at 17:56
0

Thank you for the quick answers!

With this information when I need a function within a class which is not using instances of the class I would then

  1. put a function inside the class
  2. call the function from the class methods with the leading self
  3. define the function as static method (without self as paramter), because the instance not used within the function

Thank you also for the link in one of the comments to the article, where the background is explained:

Meaning of @classmethod and @staticmethod for beginner?

import random

class SillyPerson:

    def __init__(self, FirstName, LastName):
        self.FirstName  = self.SillyName(FirstName)
        self.LastName   = self.SillyName(LastName)

    def __str__(self):
        return (f"Name is {self.FirstName} {self.LastName}")


    @staticmethod
    def SillyName (name):
        """ return sillyname if a not 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)
Nisse
  • 43
  • 7
-1
import random

class SillyPerson:

def __init__(self, FirstName, LastName):
    self.FirstName  = self.SillyName(FirstName)
    self.LastName   = self.SillyName(LastName)

def __str__(self):
    return (f"Name is {self.FirstName} {self.LastName}")


def SillyName (self,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)
Nirob
  • 29
  • 5
  • just use a `@staticmethod`, the argument `self` is not used anyway, also fix indentation – Matiiss Dec 22 '21 at 18:00
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 22 '21 at 19:09