python


Attribute in a Class immediately runs at the wrong time?


I am fairly new to Python and I am learning how classes and methods interact by creating a text-based game. The code runs great, however, my question lies in the Name(object) class. Wherever I put it in the code, (in the beginning or in the middle as shown below) I will always be prompted with an input. I suspect it may be because of the attribute name_new that prompts raw_input("> "), however, I was wondering if there was a way to prevent or change when the Class Name() is prompted.
class Character(object):
def __init__(self, name, weapon, spec_ability, health):
self.name = name
self.weapon = weapon
self.spec_ability = spec_ability
self.health = 100
def special_ability(self):
special = False
rand_num = str(random.choice(rdm))
if '1' in rand_num or '2' in rand_num or '3' in rand_num:
special = True
if special:
print "Your special ability is ready."
return True
else:
return
else:
print "Your special ability is not ready."
def Critical_Chance(self):
crit = False
rand_num = str(random.choice(rdm))
if '1' in rand_num or '2' in rand_num or '3' in rand_num:
crit = True
if crit:
print "Critical hit incoming."
return True
else:
return
class Warrior(Character):
def __init__(self, name, weapon, spec_ability, health, armor):
super(Warrior, self).__init__(name, weapon, spec_ability, health)
self.armor = armor
class Mage(Character):
def __init__(self, name, weapon, spec_ability, health, cloak):
super(Mage, self).__init__(name, weapon, spec_ability, health)
self.cloak = cloak
class Rogue(Character):
def __init__(self, name, weapon, spec_ability, health, boots):
super(Rogue, self).__init__(name, weapon, spec_ability, health)
class Name(object):
name_new = raw_input("> ")
def start():
print """\nWelcome to the world of _______. \n
You are a young hero or heroine
in search of the gold that hides within the Mountains of _____.
In order to obtain the gold and treasure that lies within the
mountains, you must battle great monsters and face dangerous
perils."""
print "Will you pursue such adventure? Or will you refuse?"
choice = raw_input("> ")
if "Yes" in choice or "yes" in choice:
Introduction()
elif "No" in choice or "no" in choice:
sys.exit()
else:
print "You typed: %s. \nPlease try again." % choice
start()
def Introduction():
print "Thank you for joining in on this adventure..."
print "Well, welcome to your adventure for the gold."
print "You will encounter dangerouse quests and enemies, but you will be\
rewarded in the end."
print "Now, what class will you be?\n\
Warrior Mage Rogue"
char_choice = raw_input("> ")
verynew_name = Name()
name_choice = Name.name_new
if "Warrior" in char_choice or "warrior" in char_choice:
name_choice = Warrior(name_choice, None, None, None, None)
print name_choice.name
print name_choice.weapon
print name_choice.spec_ability
print name_choice.health
print name_choice.armor
elif "Mage" in char_choice or "mage" in char_choice:
name_choice = Mage(name_choice, None, None, None, None)
print name_choice.name
print name_choice.weapon
print name_choice.spec_ability
print name_choice.health
print name_choice.cloak
elif "Rogue" in char_choice or "rogue" in char_choice:
name_choice = Rogue(name_choice, None, None, None, None)
print name_choice.name
print name_choice.weapon
print name_choice.spec_ability
print name_choice.health
print name_choice.boots
else:
print "You must pick a class."
start()
print "Our story starts in the town of Larton."
#super(Larton, self).enter()
start()
When you run your program, the module-level code is executed. This includes your Name class.
class Name(object):
name_new = raw_input("> ")
This creates the class Name and also executes the code within the class. Which is why you're prompted to enter a name.
If you want to be able to prompt the user for a name like this
verynew_name = Name()
you have to change your Name class so that raw_input is executed when you instantiate the class (because that's what Name() does, it creates an instance of Name):
class Name(object):
def __init__(self):
self.name_new = raw_input("> ")
(Note that instead of name_choice = Name.name_new you'll have to use name_choice = verynew_name.name_new.)
define constructors for your Character class and subclasses that don't take a name as a paramter:
e.g.
class Warrior(Character):
def __init__(self, weapon, spec_ability, health, armor):
super(Warrior, self).__init__(weapon, spec_ability, health)
self.armor = armor
and in character class, you can define self.name to be None by default
You can always assign the name later on in the logic, by using something like
character.name = Name.name_new
As long as you do that before you actually read the value of name, you will be fine

Related Links

SELECT conditions on relations with SQLAlchemy
longest and shortest curves selected
Get the key with the maximum nested key in a python dictionary
Python fermat program only works for low numbers
How to create list of all parts of elements in NumPy array (Python list)
Encoding issue for Python tool Unidecode on CL
Accept only numbers on a python string [closed]
scrapy spider pass parameters
sending data to particular client from twisted server
Type Error, object cannot be interpreted as an index with tk message box bind commands
What is this condition testing? [duplicate]
Testing Flask login and authentication?
Pyjnius import jar file
Regex - Combining an 'or' with a 'look-behind'
Command fails in python, but not in terminal
Does ndb.toplevel break transactions?

Categories

HOME
tensorflow
cil
ssas-2012
signalr
npm
angular-cli
backup
steam
concourse
rfc
specflow
codeblocks
internet-explorer-11
ipfs
google-classroom
powershell-v3.0
oclint
flexbox
ctypes
gwtp
pdo
jquery-terminal
bar-chart
arraylist
quartus
ada
zoho
embedly
url.action
apply
avplayeritem
azure-servicebus-queues
spring-test
bcrypt
tfs2013
pdfsharp
shopping-cart
katharsis
jenkins-job-dsl
emv
google-api-dotnet-client
twitter-bootstrap-2
preg-grep
spring-insight
parse-android-sdk
dql
common.logging
code-composer
jdbi
amd
python-idle
dojox.grid.datagrid
openweathermap
fqdn
ti-basic
gauss
tiddlywiki
xmgrace
spell-checking
maintenance
text-classification
tcserver
etherpad
httplib2
jszip
python-hypothesis
emgu
project-template
pspice
ebtables
pydio
gitweb
multifile-uploader
emokit
post-processing
eml
except
servlet-3.0
test-class
lemoon
datainputstream
android-cursoradapter
uialertview
apigee-baas
viper-architecture
shift-jis
chaining
belongs-to
utf-32
proximity
fragment-tab-host
x-ua-compatible
node-inspector
log4cplus
csplit
ksoap2
dynamic-proxy
gfs
jqmobi
html-form-post
windows-update
database-permissions
fluidsynth
arbor.js
zend-framework-modules
mpmovieplayer
responsetext
isolatedstorage
fileutils
querystringparameter
datacontract
dcpu-16
junit3
for-xml-path
camtasia
google-instant
graniteds

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App