passing variables with inheritance [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to practice OOP by making a class selection program
# let's make a character selection program
class player:
def __init__(self, username, age, weight, height, gender):
self.username = username
self.age = age
self.weight = weight
self.height = height
self.gender = gender
class soldier(player):
strength = weight*height*2
print strength
print "Please enter the following"
player_username = raw_input("Please enter a username: ")
player_age = input("Please enter your age: ")
player_weight = input("Please enter your weight: ")
player_height = input("Please enter your height: ")
player_gender = raw_input("Please enter your gender: ")
player_character_class = raw_input("Please enter a player class: ")
character_obj = player(player_username, player_age, player_weight, player_height, player_gender)
print soldier.strength
However, I get the error
Traceback (most recent call last):
File "character_select.py", line 11, in <module>
class soldier(player):
File "character_select.py", line 12, in soldier
strength = weight*height*2
NameError: name 'weight' is not defined
Not really sure how how weight isn't defined. I thought I inherited it by passing "player" into "solder". Could someone help me on this?
Thank you!

Since you assign attributes to your player in __init__(), they don't get created until player is instantiated. However, in your soldier class, you're trying to set class attributes at class creation time based on variables that don't exist at that time, because they only exist on instances (of a different class, no less).
I think what you probably want to do is write an __init__() method for soldier. (I have also taken the liberty of capitalizing your class names per PEP 8. This helps keep track of which names refer to classes, i.e. templates for constructing objects, and which to instances of the classes.)
class Soldier(Player):
def __init__(self, username, age, weight, height, gender):
# call parent class to set up the standard player attributes
Player.__init__(self, username, age, weight, height, gender)
# now also define a soldier-specific attribute
self.strength = weight*height*2
And then instantiate the Soldier class rather than the Player class, since you want a soldier:
character_obj = Soldier(player_username, player_age, player_weight, player_height, player_gender)
print character_obj.strength
I should further note that this:
class Soldier(Player):
is not a function call. You are not passing Player to Soldier. Instead you are saying that Soldier is a kind of Player. As such, it has all the attributes and capabilities of a Player (which you do not need to specify again, that's the whole point of inheritance) plus any additional ones you define in Soldier. However, you do not have direct access to the attributes of Player (or a Player instance) when declaring Soldier (not that you would ordinarily need them).

Soldier is a class, yet you haven't instantiated it anywhere. You've tried instantiating a player, with character_obj, but when you attempt to print soldier.xxx it's looking at the class, not any object.

I took the liberty of correcting some errors/misconceptions in the code - see if this is helpful:
# let's make a character selection program
class Player:
def __init__(self, username, age, weight, height, gender):
self.username = username
self.age = age
self.weight = weight
self.height = height
self.gender = gender
class Soldier(Player):
def __init__(self, *args):
# First of all, in order to actually inherit the attributes of "player", you need to invoke the __init__ function for "player":
Player.__init__(self, *args) # The *args business is to send any arguments that can be handled by the generic player constructor to that player constructor.
# You probably want to work on the instance variable "strength", so use self.strength, self.weight, and self.height
self.strength = self.weight*self.height*2
# print strength
print "Please enter the following"
player_username = raw_input("Please enter a username: ")
player_age = input("Please enter your age: ")
player_weight = input("Please enter your weight: ")
player_height = input("Please enter your height: ")
player_gender = raw_input("Please enter your gender: ")
player_character_class = raw_input("Please enter a player class: ")
# I'm guessing you actually wanted to make the player a "soldier", not a generic "player"
character_obj = Soldier(player_username, player_age, player_weight, player_height, player_gender)
print character_obj.strength
Here is the output:
Please enter the following
Please enter a username: Brionius
Please enter your age: 92
Please enter your weight: 50
Please enter your height: 7
Please enter your gender: yes
Please enter a player class: super soldier
700

Related

creating an object from user input

So I'm fairly new to python and I wanted to make a program that creates an object of a class from the user input, so I don´t have to make 10 empty profiles. I´ve tried it like this, knowing that it'll be false, but I think it demonstrates my problem.
class Profile():
def __init__(self, weight, height):
self.weight = weight
self.height = height
def create_object():
name = input("What's your name?")
new_weight = input("What's your height?")
new_height = input("What's your weight?")
name = Profile(new_weight, new_height)
return name
If i now want to create the object:
>>> create_object()
What's your name? test
What's your height? 23
What's your weight? 33
<__main__.Profile object at 0x000002564D7CFE80>
>>> test()
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
test()
NameError: name 'test' is not defined
or should I use a dictonary and if yes, how?
In my experience, it is not necessary to specifically name each instance of a class. Instead, you could do as some commenters suggested and add each new object to a dictionary, like so:
object_dict = {}
for i in range(10):
name = input("what's your name")
object_dict[name] = create_object()
The difference to note here is that I moved the name portion of your funtion to outside of the create_object() scope. To my knowledge, there are no "easy" or "clean" ways to create variables in python with a string as the user input (especially not if you are new to python).
If what you are doing doesn't necessarily need the name, and the user details are only for data storage, then it would be more concise to save the name as a property in your class, like so:
class Profile():
def __init__(self, weight, height, name):
self.weight = weight
self.height = height
self.name = name
And then when you generate the profiles, simply add them to a list:
for i in range(10):
object_list.append(create_object())
One last thing, the input method always returns a string. So if you plan to do math with the weight and height values, you will need to change the input from a string to a number, which you can do by surrounding the input() call with int() like
weight = int(input("What's your weight?"))
height = int(input("What's your height?"))

Does this look like a good way to use a class?

I have a class, and a Python script that calls functions from the class.
The class is called User_Input_Test. The script is called input_test.py.
input_test.py will request input from the user by using one of the class functions/methods: get_user_input(self). It is then supposed to print out whatever the user entered, through the use of the second function/method called show_output(self).
It generates an error:
User_Input_Test.show_output()\
File "/Users/michel/Python_Projects/User_Input_Test.py", line 49, in show_output\
""")
AttributeError: type object 'User_Input_Test' has no attribute 'brand'
It looks like show_output(self) is not able to see the data pulled in from the user via get_user_input(self).
Would you say that is the correct interpretation of the error? And most importantly: Is there a solution for this, or am I trying to use a class for something it was never designed for?
user_input.py:
from User_Input_Test import User_Input_Test
import time
#User_Input_Test.__init__(self, name, brand, engine, doors, fuel_type, aircon, weight, mpg, tax)
print("This little application collects data about your car")
print("Please fill out the following questionnaire:")
uname = input("What is your first name?:")
User_Input_Test.get_user_input()
print(f"{uname}, these are your car's attributes: ")
time.sleep(2)
User_Input_Test.show_output()
User_Input_Test.py
class User_Input_Test:
"""
Small Class that asks the user for their car attributes and can print them out
Attributes:
brand(string)
engine(string)
....
"""
def __init__(self, brand, engine, doors, fuel_type, aircon, weight, mpg, tax):
self.brand = brand
self.engine = engine
self.doors = doors
self.fuel_type = fuel_type
self.aircon = aircon
self.weight = weight
self.mpg = mpg
self.tax = tax
#classmethod
def get_user_input(self):
while 1:
try:
brand = input("What is the Brand & Model of your car? (e.g. 'Mercedes Benz, E-Class'): ")
engine = input("Engine Cylinders and Displacement (e.g. '4 Cylinders, 2.1 Liters'): ")
doors = input("How many doors does it have?: ")
fuel_type = input("What fuel does it use? (e.g. Petrol, Diesel, LPG): ")
aircon = input("Does it have Airconditioning? (Yes/No): ")
weight = input("How much does it weight in KG? (e.g. 1800kg): ")
mpg = input("What is the fuel consumption in Imperial MPG? (e.g. 38mpg): ")
tax = input("How much does the UK Roadtax cost per year? (e.g. £20): ")
return self(brand,engine,doors,fuel_type,aircon,weight,mpg,tax)
except:
print('Invalid input!')
continue
def show_output(self):
print(f"""
==========================================================================
Brand Name:....................... {self.brand}
Engine:........................... {self.engine}
Number of Doors:.................. {self.doors}
Fuel Type used by the engine:..... {self.fuel_type}
Does it have Aircon?:............. {self.aircon}
Fuel consumption in Imperial MPG:. {self.mpg}
Cost of Road Tax per Year:........ {self.tax}
==========================================================================
""")
User_Input_Test.show_output() tries to call show_output on the class itself; you need to call it on the instance returned by User_Input_Test.get_user_input().
from User_Input_Test import User_Input_Test
import time
print("This little application collects data about your car")
print("Please fill out the following questionnaire:")
uname = input("What is your first name?:")
car = User_Input_Test.get_user_input()
print(f"{uname}, these are your car's attributes: ")
time.sleep(2)
car.show_output()
Note: check out PEP 8, the Python style guide, notably the naming conventions for modules and classes. In this case, I would name the module car and the class Car for more clarity and better style. Also, the argument to a classmethod is usually named cls, as self is conventionally reserved for the instance in normal methods.

How to make the use user input to create an instance of a class?

I'm making a text-based adventure game in python and would like the user to choose a race and create an instance of a race class based on their choice. For example, if the player chose a Lizardman race from this code:
def character_creation():
print("You have four choices, choose wisely")
races = ['Lizard', 'Bookshelf', 'Genie', 'Werepus']
while True:
for i, j in enumerate(races):
print(f"[{i + 1}]", j)
choice = int(input('Pick a race:'))
if choice <= len(races):
print('You are a ', races[choice])
return races[choice]
else:
continue
How would I get my code to make a race object?
character = Race('Lizardman', 'Regrowth', 20)
Each race is created by Race(Name, Passive, HP) and each race has its own passive and hp associated with it. As in, I don't want to ask the user for the passive and the HP, just the race name.
You can use classmethod here.
class Race:
def __init__(name: str, passive: str, hp: int):
self.name = name
self.passive = passive
self.hp = hp
#classmethod
def from_race_name(cls, name):
race_attributes = {'Lizardman':{'passive': 'Regrowth',
'hp': 20,
.....}
return cls(name,
race_attributes[name]['passive'],
race_attributes[name]['hp'])
This will create an instance of the class based on only name of the race. To use it call it with the class name:
liz = Race.from_race_name('Lizardman')
This will create an instance of lizardman which will automatically be assigned 'regrowth' passive and 20 hp.
Also, if you want to create a 'unique' lizardman you can still do it manually:
admiral_akbar = Race(name='Lizardman', passive='panic', hp=999)
If you want the user to only choose the race name and have everything else on default you can set the default values in the class parameters.
Here's an example:
class Race():
def __init__(self, Name: str, Passive: str = "Regrowth", HP: int = 20): # Set default values here
self.Name = Name
self.Passive = Passive
self.HP = HP
def Main():
race_name = input("Pick a race: ")
character = Race(race_name)
print(character.Name, character.Passive, character.HP)
if __name__ == "__main__":
Main()
Output if user enters 'Lizardman':
Lizardman Regrowth 20
You can still overwrite and change the the Passive and the HP as so:
character = Race(Name = race_name, Passive = "Something", HP = 100)

Python Object Oriented Programming

I have to write a program to demonstrate a customer using their credit card to check out, I have spent a few hours trying to figure out how to do it and have provided my code below.
I have to make a class, then use it in a main function.
This is what I have so far:
class Customer:
def __init__(self, customer_name, credit_card_num, credit_security_code, debit_card_num, debit_pin):
self.customer_name = name
self.credit_card_num = credit_num
self.credit_security_code = credit_code
self.debit_card_num = debit_num
self.debit_pin = debit_pin
def inputCardInfo(self):
self.customer_name = str(input("Enter your name: "))
self.credit_card_num = str(input("Enter credit card Number: "))
self.credit_security_code = str(input("Enter 3-digit security code: "))
self.debit_card_num = str(input("Enter debit card number: "))
self.debit_pin = str(input("Enter 4-digit PIN: "))
then the main function:
from customer import Customer
def main():
print("Welcome to Wake-Mart. Please register.")
customer_name = input("enter name: ")
customer1 = Customer(customer_name)
print("Registration completed")
main()
I don't know the correct way to call the class methods. I feel if I can figure out how to make one of these work I can figure out the rest.
If you want to understand behaviors and properties more deeply I would recommend making a separate behavior for each value. (get_credit_num, get_debit_num, etc.)
Then, in your main, just call each function individually to get each value.
And to clarify, "class functions", or behaviors, are just things an object can do. You call them the same way you would any function, with the only difference being you put the name of the instance you are calling this behavior for before the function to replace "self". So if you were calling "InputCardInfo" for the object customer1, you would do it like so:
customer1.InputCardInfo(other parameters)
Your code as-is will not work because you are not passing all required parameters when initializing your class.
customer1 = Customer(customer_name)
All of the additional parameters besides self included in your def __init__(self, var1, var2, var3): needs to be passed to the class instance when initializing. There are also variable naming issues with your code but I hope my example below clarifies things for you.
A quick note first to help you better understand: self.customer_name = name does not make sense in your code because there is no parameter named name included in the __init__() method. You must associate an instance variable (self.whatever) to a known variable name passed in through the __init__(self, external_var) method so that self.whatever = external_var. Then, and only then, can you use class methods to call self.whatever and expect to receive the data you passed from external_var. Also, additional parameters you include after self in __init__(self, ..., ...) MUST be passed as variables when creating a class instance.
class Customer:
def __init__(self, customer_name, credit_card_num, credit_security_code, debit_card_num, debit_pin):
self.customer_name = customer_name
self.credit_card_num = credit_card_num
self.credit_security_code = credit_security_code
self.debit_card_num = debit_card_num
self.debit_pin = debit_pin
name = 'Mike'
cc_num = '0000 0000 0000 0000'
code = '111'
debit_num = '1111 1111 1111 1111'
pin = '1234'
new_customer = Customer(name, cc_num, code, debit_num, pin)

i am creating two classes student(base) and detail.Why wont studen will access the variables roll_No ,class.?

![enter image description here][1]i am creating two classes student(base) and detail .Detail is inheriting all the attributes of base .I am initializing the attributes (roll_no,name and class_stud)subclasses of base with students object of subclass created with student.subclasses().Here is the code:
student=type('student',(object,),{})
def getinfo():
for studen in student.__subclasses__():
studen.roll_no=input("enter the roll number")
studen.name=input("enter the name of student")
studen.class_stud=input("enter the class")
def printinfo():
print('roll number ',roll_no,name,class_stud)
detail=type('detail',(student),{'info':getinfo(),'print':printinfo()})
ob=detail()
ob.info
ob.print
I have never seen anyone create Python classes this way, except to see if they could. You have quite a few errors, but this might do what you want (although that is not clear):
student=type('student',(object,),{})
def getinfo(self):
for studen in student.__subclasses__():
studen.roll_no=input("enter the roll number: ")
studen.name=input("enter the name of student: ")
studen.class_stud=input("enter the class: ")
def printinfo(self):
print('roll number ',self.roll_no,self.name,self.class_stud)
detail=type('detail',(student,),{'info':getinfo,'print':printinfo})
ob=detail()
ob.info()
ob.print()
As you can see, your main error was in not passing the object into the methods. Other errors included a missing comma after student when defining detail. See also comments by #abarnert.
This is a horrible way of defining a class in Python.
EDIT:
I have no idea why you are iterating over subclasses, this is probably what you meant for getinfo:
def getinfo(self):
self.roll_no=input("enter the roll number: ")
self.name=input("enter the name of student: ")
self.class_stud=input("enter the class: ")

Categories

Resources