+ 1
Why does this output weird things and not what I want it to. class goblin: def __init__(self, hitpoints, health): self.hitpoints = hitpoints self.health = health gragnack=goblin("10",100) print(gragnack)
4 Answers
+ 4
You've asked this question already... but we can say why, because we don't have all the code ( what's in the "gragnack" variable? ), neither than the output ( "weird things" isn't precise )...
If you want to print/output the word "gragnack" and not the content of a variable named "gragnack", you need to quote him:
print("gragnack")
+ 2
'''
Why does this output weird things
and not what I want it to?
'''
class Goblin:
def __init__(self, hitpoints, health):
self.hitpoints = hitpoints
self.health = health
gragnack=Goblin("10",100)
# you are printing some of the object specifications
# ie information about the object
print(gragnack)
# to access more info on the object
# there are additional methods
# if you are interested, some are.
print(id(Goblin))
print(dir(Goblin))
print(type(Goblin))
# However if all you want is to
# access the object properties use
# the example below to retieve them
# directly
# or write a method for your class
# to do the job
print(gragnack.hitpoints)
print(gragnack.health)
0
Thank you guys very much
0
you can define the __str__ method to print what you want.
For instance, you might want to do:
def __str__(self):
return f'Hitpoints: {self.hitpoints}, Health: {self.health}'
using Python 3.6 f-strings (formatted strings)