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

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().

Related

Functions homework

My apologies as I am very new to Python and coding in general but I am trying an exercise on creating functions and formatting all in the same. Here I have a function I wrote for practice. But I can't get it to run correctly. What am doing wrong with creating this function.
My code:
def greeting(name):
name = input("What's your name: ")
return "Hi %s" % name
print(greeting())
The error:
TypeError: greeting() missing 1 required positional argument: 'name'
Thank you for your help. :)
You don't need to give name as a parameter to the greeting function.
Try this:
def greeting():
name = input("What's your name: ")
return "Hi %s" % name
print(greeting())
You don't want to take name as an argument, because you are creating that variable within the function in your call to input()
def greeting():
name = input("What's your name: ")
return "Hi %s" % name
You also do not need to print() the function, because it's return value (a string) is printed by default. If you saved the return value of greeting() into an object, you could then print that object
the_greeting = greeting()
print(the_greeting)

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()

Class isn't outputting arguments/doing anything? (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()

How to use functions inside #classmethod decorator

When using #classmethod this is passed first instead of self. Now inside the method with this decorator i need to call functions that are not defined inside this decorator but are defined in the class. How can i call the two functions get_int_input and get_non_int_input so that i can pass them to the return cls(name,pay_rate,hours) statement?
class Employee(object):
def __init__(self,name,pay_rate,hours):
self.name = name
self.pay_rate = pay_rate
self.hours = ("mon","tues","wed","thursday","friday","saturday","sunday")
def get_int_input(prompt):
while True:
pay_grade = raw_input(prompt)
try:
i = int(pay_grade)
except ValueError:
print "Int Only"
else:
return i
def get_non_int_input(prompt):
while True:
a_name = raw_input(prompt)
try:
i = int(a_name)
except ValueError:
return a_name
else:
print " Strings Only"
#classmethod
def from_input(cls):
day_count = 1
hours = ("m","tue","w","thur","f","s","sun")
while day_count <= 7:
for day in hours:
day = input(" Enter hours for day " + str(day_count) + "--- ")
day_count += 1
return cls(name,pay_rate,hours)
name = get_non_int_input("\n Enter new employee name\n")
pay_rate = get_int_input("Enter pay rate ")
employee = Employee.from_input()
print str(employee)
You would add the #staticmethod decorator before the other two classes. Since they don't take either the Employee class or one of its instances as their first argument, they operate independently of a particular class or instance, and in this sense are "static".
A method decorated in this manner is an attribute of its containing class, and is called as a class attribute, for example:
>>> class Foo(object):
... #staticmethod
... def bar():
... print 'called the static method'
...
>>> Foo.bar()
called the static method
This works the same way if you're calling Foo.bar() from inside one of Foo's class methods.
There are some other problems here, though - I would advise you to seek more comprehensive review and advice.
You defined get_int_input and get_non_int_input inside the Employee class, which means that (by default) they should take an instance of Employee as the first argument. Your code is breaking that rule, which is probably the cause of problems.
Use #staticmethod decorator to indicate that get_int_input and get_non_int_input should not take an instance of Employee as the first argument.
you seem to be missing some core concept of programming
you should probably look up namespaces and scope in google.
you should probably not talk down to john.r.sharp as he is very helpful and I would hazard a guess that if you continue programming you will have many many more problems that you come to SO for help with
all that said here is your fixed code
#first pull these two functions out of your class they have nothing to do with employee
#they should just be normal functions #
#... if you wanted to make them part of a class make an input class and add them as static methods to that
def get_int_input(prompt):
while True:
pay_grade = raw_input(prompt)
try:
i = int(pay_grade)
except ValueError:
print "Int Only"
else:
return i
def get_non_int_input(prompt):
while True:
a_name = raw_input(prompt)
try:
i = int(a_name)
except ValueError:
return a_name
else:
print " Strings Only"
class Employee(object):
def __init__(self,name,pay_rate,hours):
self.name = name
self.pay_rate = pay_rate
self.hours = ("mon","tues","wed","thursday","friday","saturday","sunday")
#classmethod
def from_input(cls):
day_count = 1
hours = ("m","tue","w","thur","f","s","sun")
while day_count <= 7:
for day in hours:
day = input(" Enter hours for day " + str(day_count) + "--- ")
day_count += 1
#name and pay_rate must be defined prior to using them in your return function ...
name = get_non_int_input("\n Enter new employee name\n")
pay_rate = get_int_input("Enter pay rate ")
#now that you have all the info just return it
return cls(name,pay_rate,hours)
employee = Employee.from_input()
print str(employee)

Categories