0

I'm making a videogame in Python and I would like to avoid writing all the self.parameter1 = parameter 1 in each class I'm creating.

I looked up for a way to automatize this process both in YouTube and Stack Overflow, but I found nothing.

Is also possible I'm making a mistake creating a class that contains so many parameters?

P.S: I tried this idea of using a function to automatize the process, but maybe because I'm new to programming, I'm making mistakes, or maybe was just a bad idea (I get mistakes about unresolved references of self, a, b, ...).

Just in case I'll leave the code I tried here:

def lazy:
    for parameter in parameters:
        return self.parameter == parameter

global parameters (a, b, c, d, e, f)

class npc:
    def __init__(self, parameters):
        lazy()
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Maki
  • 3
  • 2
  • 2
    Six parameters isn't really a lot. But if that bothers you, you could always pass a single dictionary. – alex Jan 04 '22 at 23:09

1 Answers1

0

What you need to do is to make a parent class. The classes that have the same attributes can instead inherit the attributes from the parent class.

Example:

class ExampleParentClass:
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

    def foo(self):
        # do something


class ExampleChildClass(ExampleParentClass): # Inherits from the parent class
    def __init__(self, arg1, arg2, arg3):
        ExampleParentClass.__init__(self, arg1, arg2) # Initialize the parent class
        self.arg3 = arg3

    def it_works(self):
        """This works because the child class has the same 
           attributes as the parent class"""
        print(self.arg1)
        foo(self.arg2)

Learn more about inheritance here.

Cameron
  • 389
  • 1
  • 9