Skip to content
Advertisement

Creating a class property using a function

I found this fantasy name generator here.

I am trying to adapt the code to suit my purpose. I want to create an NPC name automatically, using the function name_gen within the class NPC. With the NPC characteristics being:

JavaScript

The code from the name generator I need is the following:

JavaScript

Now the only thing I think I still need to do, is to generate the name from within the class NPC. I thought doing something like:

JavaScript

But I don’t understand how to make the name_gen function check the class NPC properties, so that it generates the desired name.

Could someone perhaps help me out?

EDIT

Thank you for all the solutions! I am pretty new to Python; In order to test Samwises solution, I tried to run it as a separate script (in order to check whether I would get a name) with the code below. It does however not print anything. I’m putting this in an EDIT because I think it might be a trivial question. If it is worth posting a separate question, please let me know:

JavaScript

Advertisement

Answer

Your name generator is a little over-complicated IMO. I’d suggest wrapping all the file reading and name selection stuff in a simple class so you can define it once and then instantiate it for each of your name lists. Putting the file reading part in __init__ means you only do it once per list instead of re-reading the file each time you need to pick a name.

JavaScript

Now you can define three NameChoosers and a name_gen function that picks among them:

JavaScript

And now you can define an NPC class that takes age and gender as arguments to the constructor, and picks a random name using name_gen():

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement