Class isn't outputting arguments/doing anything? (Python) - python

class Fridge:
def __init__ (self, food, quantity):
self.food=food
self.quantity=quantity
def UserEntry(self):
if input=="milk":
print("you got milk!")
else:
print ("What do you want?")
def DisplayFridge(self):
print("Fridge_item#1 :" , self.food, "Quantity:" , self.quantity)
When I attempt to instantiate the class, such as:
test= Fridge
and as soon as a I open the parenthesis in order to instantiate the class such as follows:
test = Fridge (
I am presented with the arguments that were passed to the class constructor/initialization method. (i.e. food and quantity).
With that in mind then....I am at a bit of a loss as to why I am not getting any output. nor, am I being asked for input, etc.

You are not getting any input this way, you should try :
class Fridge:
def __init__ (self, food, quantity):
self.food=food
self.quantity=quantity
def UserEntry(self):
var = raw_input("Please enter something: ")
if var=="milk":
print("you got milk!")
else:
print ("What do you want?")
def DisplayFridge(self):
print("Fridge_item#1 :" , self.food, "Quantity:" , self.quantity)
But there is serious lack of logic in your code :
Why UserEntry is never used ?
How do you use Fridge ?
You userEntry method will never change your self.food variable.

If you're making an instance, you type
test = Fridge(
And then it doesn't show you "the arguments that were passed to the class constructor/initialization method", but it shows you what you have to pass in order to make an instance.
E.g.
test = Fridge("milk", 10)
And now it holds 10 milks. Try
test.UserEntry()
test.DisplayFridge()

Related

Python Class and encapsulation methods

I'm new to OOP and this is my first shot at creating a Python class. I am trying to make my 3 variables private and so that only the methods update the info (enforce encapsulation). It seems that if I remove the setters and getters methods from my class, it has no impact on my code (must be the initializer method doing the work?). What can I do to improve this? Thanks.
Edit- i've updated my code and removed the init. My getters are not working now.
#Instantiate a new Pet Instance.
myPet = Pet()
#Get input from user.
myPet.setName = input("Enter the pet's name: ")
myPet.setTypes = input("Enter the pet's type (Dog, Cat, Bird, etc.): ")
myPet.setAge = input("Enter the pet's age (in years): ")
while myPet.setAge.isalpha():
print()
print("Age cannot contain numbers. Try again.")
myPet.setAge = input("Enter the pet's age (in years): ")
#Call the showPetInfo module using new instanced object.
myPet.showPetInfo()
class Pet:
#Fields of the Pet Class.
__PetName = ""
__PetType = ""
__PetAge = ""
#Setter methods.
def setName(self,name):
self.__PetName = name
def setTypes(self,types):
self.__PetType = types
def setAge(self,age):
self.__PetAge = age
#Getter methods.
#property
def getName(self):
return self.__PetName
#property
def getType(self):
return self.__PetType
#property
def getAge(self):
return self.__PetAge
def showPetInfo(self):
print("\n \n \n \n")
print("Here is your pet's information. Your pet's name is {}, it is a {} and it is {} years old.".format(self.getName,self.getType,self.getAge))
main()
you are unfortunately right, they use to say setters/getters are contracts doing restriction for adults... (if I tell you "dont touch it" then you shoulntd touch it) but there is nothing restricting you and you can modify them!
same "feature" can be observed with "constants"... do in the jupyther or the terminal this
import math
math.pi = 1
a = math.pi
a
math.pi
and you will see that you now modified the constant pi value to 1
many sugest to usse properties but that is not a capsulation at all, that is just sugar syntax for the same "adults contract" IMHO :)
so to your question
What can I do to improve this?
document the code you are writing so the other part using it is aware about how the code, instances states in objects must be handled

NameError trying to use a custom class

I am new to Python, am just learning Classes, and am trying to write a "personal info" program:
This is my code:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
def addresses(self, add):
add = raw_input("What is your adress?")
self.addresses = add
def ages(self, age):
age = raw_input("What is your age?")
self.ages = age
def numbers(self, number):
number = raw_input("What is your phone number?")
self.numbers = number
PersonalInfo()
def print_names():
info = PersonalInfo()
print "Name:", info.names(name)
print "Address:", info.addresses(add)
print "Age:", info.info.ages(age)
print "Phone number:", info.numbers(number)
print_names()
But when I run it it says this:
NameError: global name 'add' is not defined
Can someone please help me?
There are several issues with your code other than the NameError and I strongly suggest you read more on python classes:
https://docs.python.org/2/tutorial/classes.html
https://www.tutorialspoint.com/python/python_classes_objects.htm
https://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Classes
I'll run you through those issues.
First, the NameError occurs because the add variable was not defined. The same applies to all other arguments you provided in your print statements.
Second, there are issues with the way you define the class methods:
class PersonalInfo():
def names(self, name):
name = raw_input("What is your name?")
self.names = name
Here, you are re-assigning the name variable to the return value of raw_input so there's no sense in setting it as an argument in the first place. Also, by stating self.names = name you are re-assigning the class method to the string that is returned by raw_input!
Third, you have to decide whether you want to provide the information when calling the methods, or using raw_input. Here's a working example of your code, assuming you want to use raw_input
class PersonalInfo():
def names(self):
name = raw_input("What is your name?")
self.name = name
def addresses(self):
add = raw_input("What is your adress?")
self.address = add
def ages(self):
age = raw_input("What is your age?")
self.age = age
def numbers(self):
number = raw_input("What is your phone number?")
self.number = number
def print_names():
info = PersonalInfo()
# Get information
info.names()
info.addresses()
info.ages()
info.numbers()
# After getting the info, print it
print "Name:", info.name
print "Address:", info.address
print "Age:", info.age
print "Phone number:", info.number
print_names()

Beginner Python Classes - changing the attribute value with user input

I am just learning classes in Python and for the past day I am stuck with the below.
I am trying to use a user input (from the main() function) to change the value of an attribute in the class.
I have been throught the #property and #name.setter methods that allow you to change the value of a private attribute.
However I am trying to find out how you can use user input to change the value of an attribute that is not private.
I came up with the below but it does not seem to work. The value of the attribute remains the same after I run the program. Would you have any ideas why?
class Person(object):
def __init__(self, loud, choice = ""):
self.loud = loud
self.choice = choice
def userinput(self):
self.choice = input("Choose what you want: ")
return self.choice
def choiceimpl(self):
self.loud == self.choice
def main():
john = Person(loud = 100)
while True:
john.userinput()
john.choiceimpl()
print(john.choice)
print(john.loud)
main()
In choiceimpl you are using == where you should use =.
Like stated before, you are using a comparison with == instead of the =.
Also you are returning self.choice in userinput as a return value, but never use it, because you set self.choice equal to input.
Shorter example:
class Person:
def __init__(self, loud):
self.loud = loud
def set_loud(self):
self.loud = input("Choose what you want: ")
def main():
john = Person(100)
while True:
john.set_loud()
print(john.loud)
main()
1) Change: '=='(comparison operator) to '='(to assign)
2) Inside class:
def choiceimpl(self,userInp):
self.loud = self.userInp
3) Outside class
personA = Person(loud) # Create object
userInp = raw_input("Choose what you want: ") # Get user input
personA.choiceimpl(userInp) # Call object method

Homework Help - Object-Oriented Programming

In my intro class, we just started the section on object-oriented programming. This class is the first I've ever been exposed to programming, and I'm really not understanding it.
We have an assignment where we have to create an Animal class, a Zoo class, and then a zookeeper program to run the information from the first two classes. I have the programs typed up based off of examples in my book, but am still not doing it correctly.
If you could look over my codes and give me some feedback or help, that would be greatly appreciated!
class Animal:
def __innit__(self, animal_type, name):
self.animal_type = animal_type
self.name = name
def get_animal_type(self, animal_type):
self.__animal_type = animal_type
def get_name(self, name):
self.__name = name
def check_mood(self, mood):
input random.txt
print random.random()
Class Zoo:
def __innit__(self):
self.__animals = animal_list
def add_animals(self, animal):
self.__animals.append(animal)
def show_animals(animal_list):
return animal_list
input Animal.py
input Zoo.py
def main():
ADD_ANIMAL = 1
SHOW_ANIMALS = 2
EXIT = 3
def get_manu_choice():
print()
print("Zoo Options")
print("-----------")
print("1. Add Animal")
print("2. Show Animals")
print("3. Exit")
print()
choice = int(input("What would you like to do? "))
while choice < ADD_ANIMAL or choice > EXIT:
choice = int(input("Please choose a valid option: "))
return choice
main()
innit should be init
Looks to me like you are missing a chunk of functionality. You need an instance of zoo, and then in response to the input, either add another animal to the zoo or print the list of animals.

__init__() takes exactly 2 arguments (1 given)?

I would like to know where am lagging, Looking for your advices..
class Student_Record(object):
def __init__(self,s):
self.s="class_Library"
print"Welcome!! take the benifit of the library"
def Student_details(self):
print " Please enter your details below"
a=raw_input("Enter your name :\n")
print ("your name is :" +a)
b=raw_input("Enter your USN :\n")
print ("Your USN is:" ,int(b))
c=raw_input("Enter your branch :\n")
print ("your entered baranch is" +c)
d=raw_input("Enter your current semester :\n")
print ("your in the semester",int(d))
rec=Student_Record()
rec.Student_details(self)
I am getting this error ..
TypeError: init() takes exactly 2 arguments (1 given)
Your Student_Record.__init__() method takes two arguments, self and s. self is provided for you by Python, but you failed to provide s.
You are ignoring s altogether, drop it from the function signature:
class Student_Record(object):
def __init__(self):
self.s = "class_Library"
print"Welcome!! take the benifit of the library"
Next, you are calling the method rec.Student_details() passing in an argument, but that method only takes self, which is already provided for you by Python. You don't need to pass it in manually, and in your case the name is not even defined in that scope.
if you do
class Student_Record(object):
def __init__(self, s):
self.s = ""
def Student_details(self):
print " Please enter your details below"
when you create the object of class Student_Record it should accept a parameter despite for itself (self). so it looks like:
record = Student_Record("text")
and in __init__ you can do whatever with the passed-in variable s. For example, self.s = s and you can call it anywhere in the class with self.s because it has been initialized.
Your code should be like this..(python indent):
class Student_Record(object):
def __init__(self,s="class_Library"):
self.s=s
print"Welcome!! take the benifit of the library"
def Student_details(self):
print " Please enter your details below"
a=raw_input("Enter your name :\n")
print ("your name is :" +a)
b=raw_input("Enter your USN :\n")
print ("Your USN is:" ,int(b))
c=raw_input("Enter your branch :\n")
print ("your entered baranch is" +c)
d=raw_input("Enter your current semester :\n")
print ("your in the semester",int(d))
rec=Student_Record()
rec.Student_details()
s in def __init__ should have a default value or you can pass a value from rec=Student_Record().

Categories