Why does my code say NameError: name 'self' is not defined' - python-3.x

Sorry if this is a really stupid question since I am terrible at python and most of my knowledge consists of the very restricted things you are taught before post 16 education. Basically I'm trying to do a coding project in preparation for when my classes start in September, and so far I've managed to get by teaching myself classes using online websites and people's online forum questions. However, I've come into a bit of a roadblock because my code keeps throwing an error. I've looked on websites and forums but they seem to be in very different situations compared to me and some of them just seem to tell me what I've done is right. The exact error given is: line 34, in returnBarbarianStats
print(self.name,"the barbarian's stats:")
NameError: name 'self' is not defined
import random
def getName():
syllables = ['en','da','fu','ka','re','toh','ko','noh','tuk','el','kar']
firstName = (random.choice(syllables))
secondName = (random.choice(syllables))
thirdName = (random.choice(syllables))
global generatedName
generatedName = firstName+'-'+secondName+'-'+thirdName
# Classes-all creatures have names generated the same way and have the same amount of health.
# The way I have selected how each subclass will be randomly chosen is having the code select a random value
# from the list and depending on which is chosen it will give a subclass.
class preset():
def _init_(self, creature, name, health=100):
self.name = generatedName
self.health = 100
getName()
self.name=generatedName
#Gives different attributes to each sub-class
class barbarian(preset):
def _init_(self, name, power=70, specialAttackPower=20, speed=50):
preset._init_(self, creature, name, health=100)
self.power = power
self.specialAttackPower = specialAttackPower
self.speed = speed
self.name = name
def returnBarbarianStats():
print(self.name,"the barbarian's stats:")
print("Health:",self.health)
print("Power damage:",self.power)
print("Special attack power damage:",self.specialAttackPower)
print("Speed:",self.speed)
class elf(preset):
def _init_(self, name, power=30, specialAttackPower=60, speed=10):
preset._init_(self, creature, name, health=100)
self.power = power
self.specialAttackPower = specialAttackPower
self.speed = speed
class wizard(preset):
def _init_(self, name, power=50, specialAttackPower=70, speed=30):
preset._init_(self, creature, name, health=100)
self.power = power
self.specialAttackPower = specialAttackPower
self.speed = speed
class dragon(preset):
def _init_(self, name, power=90, specialAttackPower=40, speed=50):
preset._init_(self, creature, name, health=100)
self.power = power
self.specialAttackPower = specialAttackPower
self.speed = speed
class knight(preset):
def _init_(self, name, power=60, specialAttackPower=10, speed=60):
preset._init_(self, creature, name, health=100)
self.power = power
self.specialAttackPower = specialAttackPower
self.speed = speed
#10 randomly generated characters.
i = 0
army = []
while i < 10:
creatures = ['barbarian','elf','wizard','dragon','knight']
creatureType = (random.choice(creatures))
if creatureType == 'barbarian':
army.append(barbarian())
elif creatureType == 'elf':
army.append(elf())
elif creatureType == 'wizard':
army.append(wizard())
elif creatureType == 'dragon':
army.append(dragon())
elif creatureType == 'knight':
army.append(knight())
i = i + 1
barbarian.returnBarbarianStats()
I've just given the whole code as I don't want to miss any important details out.

you missed self in the parameters buddy :)
[line 32]
def returnBarbarianStats():
correct it to
def returnBarbarianStats(self):

Related

How in Pyhton's OOP a class's method access to another class's method?

I am new to Python OOP and I am trying to learn the basics of Python OOP and I came across a video on YouTube that teaches the basics of it. The code is an example code from the video. I understood all of it but I am not able to understand how the class "Course's" "get_average_grade()" method is accessing the class "Student's" "get_grade()" method? Any help is highly appreciated.
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade # 0-100
def get_grade(self): #<---- This method was used inside the Course class
return self.grade
class Course:
def __init__(self, name, max_students):
self.name = name
self.max_students = max_students
self.students = []
def add_student(self, student):
if len(self.students) < self.max_students:
self.students.append(student)
return True
return False
def get_average_grade(self):
value = 0
for student in self.students:
value = value + student.get_grade() #<---- This Method is from the Student class
return value / len(self.students)
s1 = Student("Tim", 19, 95)
s2 = Student("Bill", 19, 75)
s3 = Student("Jill", 19, 65)
course = Course("Science", 2)
course.add_student(s1)
course.add_student(s2)

Getting a value from a Class Object in Python based on User Input

so I'm in the process of learning Python, so forgive any naivety.
I'm doing some practice on Classes - and I'm making it so that when a user input their car - it looks for instantiated objects and then returns the price.
I get it to work okay for "BMW" - but when I try Ferrari - it only return the price for the BMW (20k). I'm thinking it is something not right with the price_check function part of the code.
Please could you provide some guidance here? Code below:
class Car:
car_list = []
def __init__(self, make, model, price):
self.make = make
self.model = model
self.price = price
self.car_list.append(self)
#this is the part of the code that i'm stuck with
def price_check(self):
for i in Car.car_list:
if New_Car.make == self.make:
return i.price
else:
print("Not available")
BMW = Car('BMW', '1 Series', "£20,000")
Ferrari = Car('Ferrari', 'Italia', "£90,000")
New_Car = Car(
input("What is make of your car? "), input("What is the model? "), "")
print("The cost of this car is: ", New_Car.price_check())
So essentially, I want it to return the price of the Ferrari if that's what the user typed.
Thanks in advance. And, sorry for any incorrect formatting, etc...
Okay, I agree with the comments made by #Jarvis regarding errors in your code, I would also add that in Cars init the price is a required variable and should cause an error on instantiation. In addition, in price_check, since the new_car instance has already been added to the list, price_check will also examine that entry and either find None or 0 price, so will never get to the "No Price Available" return. Here's how I would implement the Class
class Car:
car_list = []
def __init__(self, make, model, price=None): #makes providing price optional
self._make = make
self._model = model
self._price = price
Car.car_list.append(self)
#property
def make(self):
return self._make
#property
def model(self):
return self._model
#property
def price(self):
return self._price
#price.setter
def price(self, val):
self._price = val
def price_check(self):
for i in Car.car_list:
if i != self and self.make == i.make and self.model == i.model:
return i.price
return "Not available"
Two issues, first you need to append to the list not bound to your instance but the one bound to your class as a class-attribute:
def __init__(self, make, model, price):
self.make = make
self.model = model
self.price = price
# use the 'class' rather than the 'instance', you need to modify a class-attribute
Car.car_list.append(self)
Second, your issue in price check
def price_check(self):
for i in Car.car_list:
# you need to compare self's make with 'i.make' (elements in list)
if self.make == i.make:
return i.price
else:
print("Not available")

Is there a way to get a random number to repopulate inside of a function after when calling the function again?

I am fairly new to Python and I know values called in a function are only there inside the function. I am trying to have a battle between a player and a boss in a small text game I am writing; however, It just keeps populating the same information each time the function is called. I feel like I am missing something. Any help would be appreciated.
The classes:
class Character:
def __init__(self, name, stats):
self.name = name
self.stats = stats
name = {
"Name": ""
}
stats = {
"Dexterity": "",
"Strength": "",
"Health": 20,
"AC": 16,
"Weapon": "",
}
damage = 2 * random.randrange(1, 7)
ability_check = random.randrange(1, 20)
initiative = random.randrange(1,20)
class Boss:
def __init__(self, name, stats):
self.name = name
self.stats = stats
name = {
"Name": "Gargamel"
}
stats = {
"AC": 16,
"Health": 15,
"Weapon": "Sword"
}
damage = random.randrange(1, 6)
initiative = random.randrange(1,20)
The functions:
def battle():
choice = input("Do you wish to continue fighting or run? F or R ")
if (choice.lower() == 'f'):
boss_battle()
if (choice.lower() == 'r'):
pass
def boss_battle():
print("The skeletal creature grabs a sword from the wall and takes a swing at you...\n")
print(f"Boss init {Boss.initiative}, Character init {Character.initiative}")
while Boss.stats["Health"] > 0 or Character.stats["Health"]:
if (Boss.initiative > Character.initiative):
boss_damage = Boss.damage
current_player_health = (Character.stats["Health"] - boss_damage)
Character.stats.update({"Health": current_player_health})
print(f"The boss did {boss_damage} damage. You now have {current_player_health} hitpoints left.")
if (Character.stats["Health"] <= 0):
print('You died!')
break
battle()
elif (Character.initiative > Boss.initiative):
player_damage = Character.damage + stat_block_str(int)
current_boss_health = Boss.stats["Health"] - player_damage
Boss.stats.update({"Health": current_boss_health})
print(f"You attacked the creature with your {Character.stats['Weapon']} and dealt {player_damage} damage.")
if (Boss.stats["Health"] <= 0):
print(f'Congratulations {Character.name["Name"]}! You have beaten the boss and claimed the treasure!')
break
battle()
You have declared classes with class variables, but have made no class instances, so the values are all fixed due to being initialize once when the class was defined.
To make a class instance, you "call" the class using parentheses, which calls your __init__ function on the instance, which sets instance variables.
Here's a small example:
import random
class Character:
def __init__(self,name):
self.name = name
self.health = 20
self.damage = 2 * random.randrange(1,7)
def attack(self,target):
print(f'{self.name} attacks {target.name}...')
target.health -= self.damage
print(f'{target.name} has {target.health} health remaining.')
# defines how to display the class instance when printed.
def __repr__(self):
return f"Character(name={self.name!r}, health={self.health}, damage={self.damage})"
fred = Character('Fred')
george = Character('George')
print(fred)
print(george)
print(f'{fred.name} can deliver {fred.damage} damage.')
fred.attack(george)
Output:
Character(name='Fred', health=20, damage=4)
Character(name='George', health=20, damage=10)
Fred can deliver 4 damage.
Fred attacks George...
George has 16 health remaining.
While true, that your using class variables when you should better use instance variables (see Instance variables vs. class variables in Python amongst others for details) I don't think it is enough to achieve your goal.
What you describe in the comment happens because the class is only setup once and from there on the class variables like damage etc. are static, meaning the random call is only executed once for the whole program. I would suggest to convert the damage variables to functions like this:
class Character:
def __init__(self,name):
self.name = name
self.health = 20
# just as a simple example
self.base_damage = 2
def damage(self):
return self.base_damage * random.randrange(1,7)
This way you will obtain a new random value for call to the function (battle round) and not just have a static value for damage inside the class.
Assuming you made instances for the character and the boss the call can look like this:
current_boss_health = bossInstance.stats["Health"] - characterInstance.damage()
If you want to take this on step further and make this a bit more pythonic you can use the #property decorator for damage:
#property
def damage(self):
return self.base_damage * random.randrange(1,7)
This way the usage of the function will look even more like your original and it hides the function call:
current_boss_health = bossInstance.stats["Health"] - characterInstance.damage

how to access to data from a class which is stored in another class in python?

This is my code. I got a problem when i want to print the information inside the class 'pokemon'
class trainer(object):
def __init__(self, name, pokemons = [], money = 0):
self.name = name
self.pokemons = pokemons
self.money = money
this is my first class which has every pokemon per trainer
class pokemon(object):
def __init__(self, name, attribute, attacks = {}, health = '==========='):
self.name = name
self.attribute = attribute
self.health = health
self.attacks = attacks
The other class where I take the pokemon to import to the other class
class fight():
def __init__(self, fighter1, fighter2):
self.fighter1 = fighter1
self.fighter2 = fighter2
def fighting(self):
if len(Trainer1.pokemons) >= 1 and len(Trainer2.pokemons) >= 1:
print('{} wanna fight against {}'.format(Trainer1.name, Trainer2.name))
keepgoing = True
print('{} got this Pokemons: '.format(Trainer1.name))
i = 0
for i in Trainer1.pokemons:
print(i)
#while (keepgoing):
else:
print('You gotta have pokemons to fight')
return False
I thought that creating a class named fight for getting in battle would be the most wise idea but I'd like to know another method to do it
Pokemon1 = pokemon('Charizard', 'Fire', attacks={'1':'ball fire', '2':'cut', '3':'fire blast', '4':'mega kick'})
Pokemon2 = pokemon('Charmander', 'fire', attacks={'1':'blast', '2':'scratch', '3':'heat', '4':'tear'})
Trainer1 = trainer('Santiago', pokemons=[Pokemon1, Pokemon2])
Pokemon3 = pokemon('Charizard', 'Fire', attacks={'1':'ball fire', '2':'cut', '3':'fire blast', '4':'mega kick'})
Pokemon4 = pokemon('Charmander', 'fire', attacks={'1':'blast', '2':'scratch', '3':'heat', '4':'tear'})
Trainer2 = trainer('Alejandra', pokemons=[Pokemon3, Pokemon4])
Okay my problem is in the class fight. when i want to print the names of the pokemons i get the following message:
Santiago got this Pokemons:
<__main__.pokemon object at 0x000002AAD9B64D00>
<__main__.pokemon object at 0x000002AAD9B92DF0>
i know that the pokemon class has various instances, but how can i access to them?
To make your life easier, I recommend that you implement the __str__ dunder method on pokemon. This will resolve the issue that you are seeing right now, and make future prints of pokemon much easier.
That would look something like this:
class pokemon(object):
def __init__(self, name, attribute, attacks = {}, health = '==========='):
self.name = name
self.attribute = attribute
self.health = health
self.attacks = attacks
def __str__(self):
return "Pokemon: %s (Health: %11s)" % (self.name, self.health)
When you print the 'Charmander' pokemon, it'll look something like this:
Pokemon: Charmander (Health: ===========)
Of course, you can change the return of the __str__ to return whatever you want out of the pokemon.

In OOP in python, are different instances of an object when initialised with a default value the same?

I am trying to understand object oriented programming. I am doing this by creating a small poker like program. I have come across a problem whose minimal working example is this:
For this code:
import random
class superthing(object):
def __init__(self,name,listthing=[]):
self.name = name
self.listthing = listthing
def randomlyadd(self):
self.listthing.append(random.randint(1,50))
def __str__(self):
return '\nName: '+str(self.name)+'\nList: '+str(self.listthing)
Aboy = superthing('Aboy')
Aboy.randomlyadd()
print(Aboy)
Anotherboy = superthing('Anotherboy')
Anotherboy.randomlyadd()
print(Anotherboy)
I expect this output :
Name: Aboy
List: [44]
(some number between 1 and 50)
Name: Anotherboy
List: [11]
(again a random number between 1 and 50)
But what I get is:
Name: Aboy
List: [44]
(Meets my expectation)
Name: Anotherboy
List: [44,11]
(it appends this number to the list in the previous instance)
Why is this happening? The context is that two players are dealt a card from a deck. I am sorry if a similar question exists, if it does, I will read up on it if you can just point it out. New to stack overflow. Thanks in advance.
For the non minimal example, I am trying this:
import random
class Card(object):
def __init__(self, suit, value):
self.suit = suit
self.value = value
def getsuit(self):
return self.suit
def getval(self):
return self.value
def __str__(self):
if(self.suit == 'Clubs'):
suitstr = u'\u2663'
elif(self.suit == 'Diamonds'):
suitstr = u'\u2666'
elif(self.suit == 'Hearts'):
suitstr = u'\u2665'
elif(self.suit == 'Spades'):
suitstr = u'\u2660'
if((self.value<11)&(self.value>1)):
valuestr = str(self.value)
elif(self.value == 11):
valuestr = 'J'
elif(self.value == 12):
valuestr = 'Q'
elif(self.value == 13):
valuestr = 'K'
elif((self.value == 1)|(self.value == 14)):
valuestr = 'A'
return(valuestr+suitstr)
class Deck(object):
def __init__(self,DeckCards=[]):
self.DeckCards = DeckCards
def builddeck(self):
suits = ['Hearts','Diamonds','Clubs','Spades']
for suit in suits:
for i in range(13):
self.DeckCards.append(Card(suit,i+1))
def shuffle(self):
for i in range(len(self)):
r = random.randint(0,len(self)-1)
self.DeckCards[i],self.DeckCards[r] = self.DeckCards[r],self.DeckCards[i]
def draw(self):
return self.DeckCards.pop()
def __str__(self):
return str([card.__str__() for card in self.DeckCards])
def __len__(self):
return len(self.DeckCards)
class Player(object):
def __init__(self,Name,PlayerHandcards = [],Balance = 1000):
self.Name = Name
self.Hand = PlayerHandcards
self.Balance = Balance
def deal(self,deck):
self.Hand.append(deck.draw())
def __str__(self):
return 'Name :'+str(self.Name)+'\n'+'Hand: '+str([card.__str__() for card in self.Hand])+'\n'+'Balance: '+str(self.Balance)
deck1 = Deck()
deck1.builddeck()
deck1.shuffle()
Alice = Player('Alice')
Alice.deal(deck1)
print(Alice)
Bob = Player('Bob')
Bob.deal(deck1)
print(Bob)
And after dealing to Bob they both have the same hands. If you have some other suggestions regarding the code, you are welcome to share that as well.
This is a duplicate of “Least Astonishment” and the Mutable Default Argument as indicated by #Mad Physicist. Closing this question for the same.

Resources