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?"))
Related
I'm trying to make a class, Player, and I'd like the user to create objects, say to add to their team.
Every tutorial will have something like this to create new players, say Jordan.
class Player:
def __init__(self, name):
self.name = name
p1 = Player('Jordan')
p2 = Player('Kobe')
But I want the user to have the ability to create new players, and they're not going to code, right?
And I would rather the object variable be just the player name, like, "Jordan", or "Kobe".
So if everything was manual, I could say,
jordan = Player('Jordan')
kobe = Player('Kobe')
So to come up with a function to have users create players, what should it look like? And what would the variable be? Any way to get it assigned as the player name? Or at least a serialized number like p1, p2, p3, ...?
def create_player():
new_player = input("Which player would you like to create? ")
name_of_variable_for_player = Player(new_player)
Ok, so follow on question.
What happens when you just have a static variable in the create function?
def create_player():
p = Player(input("What player would you like to make? ")
Use a dict instead of dynamic variables. For more details see How do I create a variable number of variables?
In this case that might look something like this:
class Player:
def __init__(self, name):
self.name = name
def __repr__(self): # Adding this for better output
cls_name = type(self).__name__
return '{}({!r})'.format(cls_name, self.name)
my_team = {}
name = input("Which player would you like to create? ")
my_team[name] = Player(name)
print(my_team)
Example run:
Which player would you like to create? Shaq
{'Shaq': Player('Shaq')}
How to turn that into a function might vary based on what you're trying to do, but you could start here:
def add_player_to_roster(roster):
name = input("Which player would you like to create? ")
roster[name] = Player(name)
my_team = {}
add_player_to_roster(my_team)
print(my_team)
I am trying to run some code that allows me to either call the name Student or Programmer from the class I called Master_programmer. Here is the code I used.
class Master_programmer:
capabilities = []
student = "SoloLearn Student"
programmer = "Programmer"
def Student(self):
return 'SoloLearn Student'
def Programmer(self):
return 'Programmer'
def __init__(self, name):
self.name = name
def add_capabilities(self, capability):
self.capabilities.append(capability)
m1 = Master_programmer(programmer)
print(m1.Student, m1.Programmer)
a.add_capabilities('Stay Inspired')
b.add_capabilities('Find Clients')
b.capability
After running the above code, I get the following error
Traceback (most recent call last):
File "./Playground/file0.py", line 21, in <module>
m1 = Master_programmer(programmer)
NameError: name 'programmer' is not defined
Now, my question is, how do I get my code to deliver the expected results? e.g when I request for the Name 'programmer' to be called up, I expect it to bring up Programmer and then allow me to add capabilities to the programmer like "Find Clients". And for Student it must be "Stay Inspired".
I guess the below code and its comments will answer your question.
class Master_programmer:
STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES = 'This is Static Var'
def __init__(self, name):
self.name = name
self.capabilities = []
self.student = "SoloLearn Student"
self.programmer = "Programmer"
def get_student(self):
return self.student
def get_programmer(self):
return self.programmer
def add_capabilities(self, capability):
self.capabilities.append(capability)
# Create instance for your class and name it coder (or whatever you like)
coder = Master_programmer('Replace me with student name')
# to call coder object's variable
# you need to call it by object name just like below
print('capabilities: ', coder.capabilities)
print(coder.programmer)
print(coder.student)
coder.add_capabilities('Stay Inspired')
coder.add_capabilities('Find Clients')
print(coder.get_student())
print(coder.get_programmer())
print('capabilities: ', coder.capabilities)
print()
# you can invoke Static variables usign directly class name
# you can invoke usign instance name as well but, it is not convention
print(Master_programmer.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
print()
# if you change Static member, it will get change for all of your instances
coder_2 = Master_programmer('Replace me with student name')
Master_programmer.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES = 'changed'
print()
# print static var using both ways
print(Master_programmer.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
print(coder.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
print(coder_2.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
m1 = Master_programmer(programmer)
print(m1.Student, m1.Programmer)
Is calling the variable programmer if you wan to refer to programmer = "Programmer" in the Master_programmer class you need to use Master_programmer.programmer instead.
Though your code will later crash if you don't initialse a and b too since you need to define them too like normal variables e.g. a = Master_programmer("EEZi") to call them and/ or work with them
Thank you all for your answers. Here is the final code that I went with and it works really well. Many Thanks to you.
class Master_programmer:
STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES = 'This is Static Var'
def __init__(self, name):
self.name = name
self.capabilities = []
self.student = "SoloLearn Student"
self.programmer = "Programmer"
def get_student(self):
return self.student
def get_programmer(self):
return self.programmer
def add_capabilities(self, capability):
self.capabilities.append(capability)
coder = Master_programmer('EEZi')
coder.add_capabilities('Stay Inspired!')
coder.add_capabilities('Find Clients')
a = coder.get_student()
b = coder.get_programmer()
capabilities = coder.capabilities
for i in range(0,1):
print(a)
print("Listen here, just", coder.capabilities[0], "\n")
print(b)
print("Hustle hard and", coder.capabilities[1])
I'm really struggling trying to understand functions and how they can be used to create attributes or properties (in this case i'm tasked with a person)
The following is my code to declare the person in a dictionary,
def format(person):
return "Name:\t" + person['name']
def display(person):
print(format(person))
person = {'name':"Bilbo Baggins"}
I then can call the display to produce;
Name = Bilbo Baggins
I then have to add to the dictionary a property storing the weight and height (say both of which are 0 for now) of my person, which i have done by;
person['height'] = 0
person['weight'] = 0
I now need to create a function (called create_person) that has the 3 parameters (name, height and weight), and modify my earlier code to use this function and alongside printing Name: Bilbo Baggins also prints the weight(in kg) and height(in m).
The overall aim of this is to find out the BMI of a person, BMI is calculated by weight/height2. I also need to add a function that takes a single person object from the previous dictionary/function as a parameter and returns the BMI of the person. Is that possible through linking the two?
class Person:
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
# This is called when you print(PERSON OBJECT)
def __repr__(self):
return self.name + " " + self.height + " " + self.weight
def BMI(self):
return (self.weight/self.height)/self.height
This allows you to create a person like so:
person_one = Person("Bilbo", 177, 72.7)
print(person_one)
bmi = person_one.BMI()
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)
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