Zak Brown Zak Brown - 2 months ago 5
Python Question

How to accept parameters in a Python class constructor?

class Druid:
def __init__(self, Attack, Defence, Speed, Money, Crit):
self.attack = DAP
self.defence = DDP
self.speed = DSpeed
self.money = DMoney
self.crit = DCC
def Druid_stat(self):
return '{} {}'.format(self.DAP, self.DDP)

Human_Druid = Druid(8, 7, 3, 50, 5)

print(Human_Druid.Druid_Stat())


then I get the errors of

Traceback (most recent call last):
File "/Users/ianbrown/Desktop/Shannara_Cronicles_ALPHA.py", line 13, in <module>
Human_Druid = Druid(8, 7, 3, 50, 5)
File "/Users/ianbrown/Desktop/Shannara_Cronicles_ALPHA.py", line 5, in __init__
self.attack = DAP
NameError: global name 'DAP' is not defined


It's probably really obvious and I've been comparing it to the tutorial code just with minor adjustments eg. class names and attributes etc.

Answer

just with minor adjustments eg. class names and attributes etc.

You need to be super careful with naming. Python doesn't know what your variables mean or how to infer one name from the other.

It may be obvious to you that Attack has the same meaning as DAP - but that's just obvious to you, not to anyone else and certainly not to Python. All it sees are names that you give to things.

So I assume what you want to achieve is this (red arrows pointing from the constructor argument to the respective instance variable):

enter image description here

Right? To do this you have to keep consistent with naming:

class Druid:
    def __init__(self, attack, defence, speed, money, crit):
        self.attack = attack
        self.defence = defence
        self.speed = speed
        self.money = money
        self.crit = crit
    def Druid_stat(self):
        return '{} {}'.format(self.attack, self.defence)

Human_Druid = Druid(8, 7, 3, 50, 5)
print(Human_Druid.Druid_Stat()) 

Note I also changed the names in the constructor, the __init__ method, to lowercase. While not technically required, it is a convention in Python to write variables in lowercase (as in attack, defence etc.), class names in CapWords form (e.g. Druid) and constants in all UPPERCASE.

Comments