I have a class Pet() and main() function as shown below. I get a syntax error, but it is not clear why.
class Pet(object):
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self, name):
self.__name = name
def set_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get__age(self):
return self.__age
def main():
name = input('What is the name of the pet: ')
animal_type = input('What type of pet is it: ')
age = int(input('How old is your pet: ')
pets = Pet(name, animal_type, age)
print('This will be added to the records.')
print('Here is the data you entered: ')
print('Pet Name: ', pets.get_name())
print('Animal Type: ', pets.get_animal_type())
print('Age: ', pets.get_age())
main()
I keep getting a syntax error for pets line
There are 2 errors in your code, first, your init method needs to be written with double underscore, like this __init__, and secondly, you are missing a ) on your age input line. If you put the code like this, it should work.
class Pet(object):
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self, name):
self.__name = name
def set_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get__age(self):
return self.__age
def main():
name = input('What is the name of the pet: ')
animal_type = input('What type of pet is it: ')
age = int(input('How old is your pet: '))
pets = Pet(name, animal_type, age)
print('This will be added to the records.')
print('Here is the data you entered: ')
print('Pet Name: ', pets.get_name())
print('Animal Type: ', pets.get_animal_type())
print('Age: ', pets.get__age())
main()
Related
class person:
def __init__(self, name, age):
self.name = name
self.name = age
def myfunc(self):
print(" Hello my name is " + self.name)
print(" my age is " + self.age)
p1 = person("Siddu", 24)
p1.myfunc()
#p1 = person("siddu", 24)
#print(p1.name)
#print(p1.age)
Two things :
you made one mistake in the init
you should cast your numeric value as a string before concatenating
You can find the answer in the python comments
class person:
def __init__(...):
...
self.name = age #should be self.age = age
def myfunc(self):
...
print(" my age is " + self.age) #change self.age by str(self.age)
Instead of self.name = age
you should have self.age = age
class Pet(object):
"""
Object that contains attributes relating to pets
Methods:
__init__: initializes a new object
__str__: prints an object
is_heavier: compares two pets' weights. Return True if self is heavier
than second, otherwise returns False.
is_older: compares two pets' ages. Returns true if self is older
than second, otherwise returns False.
Same_colour: compares two pets' colours. Returns True if colours match
Returns False if Colours don't match.
Attributes:
species: str of type of pet IE "dog" or "giraffe"
name: str listing the name of your pet IE "Joy" (She's a dog")
weight: float the weight of the pet in killograms
height: float the height of the pet in centimetres
age: int the age of the pet in years.
"""
def __init__(self, name, animal_type, age, weight, height):
self.__name = name
self.__animal_type = animal_type
self.__age = age
self.__heavier = weight
self.__taller = height
def set_name(self, name):
self.__name = name
def set_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get__age(self):
return self.__age
def get__heavier(self,heavier):
return self.__weight
def get__taller(self, taller):
return self.__height
def main():
name = input('What is the name of the pet: ')
animal_type = input('What type of pet is it: ')
age = int(input('How old is your pet: '))
pets = Pet(name, animal_type, age)
heavier = int(input('How much does your pet weight?: ')
print('This will be added to the records.')
print('Here is the data you entered: ')
print('Pet Name: ', pets.get_name())
print('Animal Type: ', pets.get_animal_type())
print('Age: ', pets.get__age())
print('Kg: ', pets.get__heavier())
main()
So This is supposed to be done by last Thursday, and I am STILL working on this assignment, and since it is quarantined so my teacher can't really help me with this work, and I kinda figure it out but it keeps giving me an error of the wrong spot of the code like the "print" is wrong or something like that.
I think something is wrong with this code, and I can't figure out why or what is wrong with this code. Can you guys please please please help me with good explanations?
the Title won't let me make my own so I HAD to choose that one. NOT MY FAULT! :)
you forgot to pass all argument to the Pet class when you initiated it
get__heavier and get__taller used not existed variables
Below is the working copy program
class Pet(object):
"""
Object that contains attributes relating to pets
Methods:
__init__: initializes a new object
__str__: prints an object
is_heavier: compares two pets' weights. Return True if self is heavier
than second, otherwise returns False.
is_older: compares two pets' ages. Returns true if self is older
than second, otherwise returns False.
Same_colour: compares two pets' colours. Returns True if colours match
Returns False if Colours don't match.
Attributes:
species: str of type of pet IE "dog" or "giraffe"
name: str listing the name of your pet IE "Joy" (She's a dog")
weight: float the weight of the pet in killograms
height: float the height of the pet in centimetres
age: int the age of the pet in years.
"""
def __init__(self, name, animal_type, age, weight, height):
self.__name = name
self.__animal_type = animal_type
self.__age = age
self.__heavier = weight
self.__taller = height
def set_name(self, name):
self.__name = name
def set_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get__age(self):
return self.__age
def get__heavier(self):
return self.__heavier
def get__taller(self):
return self.__taller
def main():
name = input('What is the name of the pet: ')
animal_type = input('What type of pet is it: ')
age = int(input('How old is your pet: '))
weight = int(input('How much does your pet weight?: '))
height = int(input('How much does your pet height?: '))
pets = Pet(name, animal_type, age, weight, height)
print('This will be added to the records.')
print('Here is the data you entered: ')
print('Pet Name: ', pets.get_name())
print('Animal Type: ', pets.get_animal_type())
print('Age: ', pets.get__age())
print('Kg: ', pets.get__heavier())
main()
I think error your generated on the basis of No or argument.
if you observe your code
def __init__(self, name, animal_type, age, weight, height):
self.__name = name
self.__animal_type = animal_type
self.__age = age
self.__heavier = weight
self.__taller = height
require total 5 argument while you passed only 3 of them
pets = Pet(name, animal_type, age)
correct format
pets = Pet(name, animal_type, age,weight,height)
I am working on a program that needs a str method. However, when I run the code, it only outputs:
What is the name of the pet: Tim
What type of pet is it: Turtle
How old is your pet: 6
How can I print out what I need from the str method?
Here is what I have.
This is the code for my class (classPet.py)
class Pet:
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self, name):
self.__name = name
def set_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get_age(self):
return self.__age
def __str__(self):
return 'Pet Name:', self.__name +\
'\nAnimal Type:', self.__animal_type +\
'\nAge:', self.__age
This is the code for my main function (pet.py):
import classPet
def main():
# Prompt user to enter name, type, and age of pet
name = input('What is the name of the pet: ')
animal_type = input('What type of pet is it: ')
age = int(input('How old is your pet: '))
pets = classPet.Pet(name, animal_type, age)
print()
main()
In the code for your main function (pet.py), you are calling print without any parameters. You need to call print with your pet instance as a parameter:
pets = classPet.Pet(name, animal_type, age)
print(pets) # see here
You also need to fix an error in your __str__ method:
the __str__ method doesn't concatenate all of its arguments to a string like the print() function does it. Instead, it must return a single string.
In your __str__ method you are seperating your different parts of the string by commas. This will make python think that it's dealing with a tuple. I propose the following solution using pythons format function:
def __str__(self):
return "Pet Name: {}\nAnimal Type: {}\nAge: {}".format(self.__name, self.__animal_type, self.__age)
The {} parts in the string are placeholders that are replaced with the arguments in the parenthesis through the format function. They are replaced in order, so the first one is replaced with self.__name, etc.
Trying my hand at Python inheritance. I need your help on how to fix an error.
I have 2 classes: Person (super class )& Contact (sub class).
I get the following error when trying to run Contact:
"Contact.py", line 3, in <module>
class Contact(Person):
TypeError: module.__init__() takes at most 2 arguments (3 given)
Thanks in advance
Below is my code:
class Person:
__name=""
__age=0
def __init__(self, name, age):
self.__name = name
self.__age = age
def set_name(self, name):
self.__name = name
def set_age(selfself, age):
self.__age = age
def get_name(self):
return self.__name
def get_age(selfself):
return self.__age
def getInfo(self):
return "Name is: {} - Age is: {}".format(self.__name, self.__age)
# ----------------------------------------------------
import Person
class Contact(Person):
__method=""
def __init__(self, name, age, method):
super().__init__(name, age)
self.__method = method
def set_method(self, method):
self.__method = method
def get__method(self):
return self.__method
def getInfo(self):
return "Name is: {} - Age is: {} - Contact Info: {}".format(self.__name, self.__age, self.__method)
person2 = Contact("Adam Smith", 19, "Email: adam.smith#abcde.net")
print(person2.getInfo())
First of all, the indentation is messed up!
If Person is in a separate file, import the file name without extension, like this:
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def set_name(self, name):
self.__name = name
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def getInfo(self):
return "Name is: {} - Age is: {}".format(self.__name, self.__age)
# ----------------------------------------------------
from person import Person # assumed your Person class is in person.py
class Contact(Person):
__method=""
def __init__(self, name, age, method):
super().__init__(name, age)
self.__method = method
def set_method(self, method):
self.__method = method
def get__method(self):
return self.__method
def getInfo(self):
return "Name is: {} - Age is: {} - Contact Info: {}".format(self.get_name(), self.get_age(), self.__method)
person2 = Contact("Adam Smith", 19, "Email: adam.smith#abcde.net")
print(person2.getInfo())
Access the parent class's private fields through its methods.
Hi i have a python file that contains the class pets and a file conatins the class people and a main file
the code is this:
the pets code:
class Pet:
def __init__(self, name, age, sound, type):
self.name = name
self.age = age
self. sound = sound
self. type = type
class Dog(Pet):
def __init__(self, name, age):
super().__init__(name, age, "How How", "Dog")
class Cat(Pet):
def __init__(self, name, age):
super().__init__(name, age, "Mewo", "Cat")
this is the peoples file:
import Pets
class Person:
def __init__(self, gender, name, age):
self.gender = gender
self.name = name
self.age = age
self.pets = []
def addPet(self, pet):
if isinstance(pet, Pets.Pet):
self.pets.append(pet)
else:
print("This is not a pet pls try again.")
def printPets():
print("He has:")
for pet in self.pets:
print("A: " + pet.type+ " Named: " + pet.name)
And this is the Main file:
from Person import Person
import Pets
def Main():
p1 = Person("Male", "Bob", 18)
p1.addPet(Pets.Cat("Mitzi", 2))
p1.addPet(Pets.Dog("Rexi", 5))
print(p1.printPets)
if __name__ == "__main__":
Main()
the output that i get is:
<bound method Person.printPets of <Person.Person object at 0x7f413e3604e0>>
what is this and how do i fix it ??
thanx.
What you need is print(p1.printPets())
You need to invoke the method.
Else what you are doing is printing the method and what Python gives you is the method type (bound), instance type to which it belongs and address of the instance.
You just need to include () inside print() like this:
print(s1.avg())