So I want to make a class based RPG, as a project to help me understand how classes work. Unfortunately, I didn't get far.
The below code is intended to make an instance of a character and have info in it like name, health, gold, exp, and the like. I am just testing the simplest of stuff right now, and I *think* that I got the name of the character to go into the instance but I can't get it back out.

class char:
    def __init__(self,name):
        self.name = name
        


a = raw_input("Name: ")
char(a)
print char(a)

Whenever I try to print the name of the instance, this comes out:
<__main__.char instance at 0x02B91F30>

Recommended Answers

All 7 Replies

What do you think it should print?

Here is a typical class example ...

class MyName:
    def __init__(self, name):
        self.name = name
    
    def print_name(self):
        print "Hi, I am", self.name
        
    def __str__(self):
        """overloads str() and hence print applied to instance"""
        return "My name is %s" % self.name
        

name = 'bob'
mm = MyName(name)
mm.print_name()  # --> Hi, I am bob 
print mm         # --> My name is bob

I am trying to make it so that it prints what the user put in

oh wait never mind >.< Thanks for that code example, I got it all figured out and I feel dumb

Member Avatar for masterofpuppets

simple config:

class Name:
    def __init__( self, name ):
        self.name = name

    def printName( self ):
        print "The user entered - ", self.name

n = raw_input( "Enter your name >> " )
mn = Name( n )
mn.printName()

:)

Member Avatar for masterofpuppets

oh wait never mind >.< Thanks for that code example, I got it all figured out and I feel dumb

ok sorry dude I was replying while you posted this :)

I am trying to make it so that it prints what the user put in

Okay, that's easy ...

class Character:
    def __init__(self, name, health, gold):
        self.name = name
        self.health = health
        self.gold = gold


name = 'rotzilla'
health = 100
gold = 1000000
rotz = Character(name, health, gold)

print rotz.name  # --> rotzilla
print rotz.gold  # --> 1000000

BTW, Python capitalizes class names more or less by convention.

oh wait never mind >.< Thanks for that code example, I got it all figured out and I feel dumb

First of all, you asked and second you got it all figured out. I would say you are not dumb! Good luck with your project! Keep asking question if you are stuck.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.