How do I make this python run program? - python

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)

Related

How to make a list inside a class static for the entire program

I'm messing around with classes and data flow and I am having difficulties creating a list of classes inside the class (to give control of the list to the class in itself).
class Person:
listOfPeople = []
def __init__(self, name, age):
self.name = name
self.age = age
self.listOfPeople = []
def set_age(self, age):
if age <= 0:
raise ValueError('The age must be positive')
self._age = age
def get_age(self):
return self._age
def AppendList(self):
self.listOfPeople.append(self)
def returnList(self):
return self.listOfPeople
age = property(fget=get_age, fset=set_age)
john = Person('John', 18)
barry = Person("Barry", 19)
john.AppendList()
barry.AppendList()
print(Person.listOfPeople)
The output is simply
[]
Let´s use this example. I want the class Person to have a list of people. That list of people has instances of the class it's in. I want the entire program to have access to this class, regardless of having an instance initialised. Is it even possible to do what I want in Python?
My expected output is a list with the 2 instances I added to the list.
Okay so you need to create the list outside the definitions first.
Then you need to change the append function to this instead, self.listOfPeople.append(self) so that the variables are added into the list when you run it your way and remove the self.listOfPeople from the __init__.
Now the listOfPeople you initialized is shared between all instances.
class Person:
listOfPeople = []
def __init__(self, name, age):
self.name = name
self.age = age
def set_age(self, age):
if age <= 0:
raise ValueError('The age must be positive')
self._age = age
def get_age(self):
return self._age
def AppendList(self):
self.listOfPeople.append(self)
def returnList(self):
return self.listOfPeople
age = property(fget=get_age, fset=set_age)
john = Person('John', 18)
barry = Person("Barry", 19)
john.AppendList()
barry.AppendList()
print(Person.listOfPeople)
for i in Person.listOfPeople:
print (i.name, i.age)
Output for first part is:
[<__main__.Person object at 0x7fcb72395150>, <__main__.Person object at 0x7fcb723954d0>]
Output for the second part is:
John 18
Barry 19
this code automatically adds new instances to Person.listOfPeople
class Person:
listOfPeople = []
def __init__(self, name, age):
self.name = name
self.age = age
Person.listOfPeople.append(self)
def set_age(self, age):
if age <= 0:
raise ValueError('The age must be positive')
self._age = age
def get_age(self):
return self._age
def AppendList(self):
self.listOfPeople.append(self)
def returnList(self):
return self.listOfPeople
def __repr__(self): #I've added __repr__
return self.name+' '+str(self.age)
age = property(fget=get_age, fset=set_age)
john = Person('John', 18)
barry = Person("Barry", 19)
# john.AppendList()
# barry.AppendList()
print(Person.listOfPeople)
the output: [John 18, Barry 19]
is this what you need?
Just get rid of this
self.listOfPeople = []
This line overrides the class attribute and creates an instance attribute with the same name - not what you want.

How do I write a Python class taking other super class objects as parameters

Lets assume that I have a class called Person, and a class that inherits this called Group. Person has an attribute called name and one called age. When I create a Group I want to pass n person objects and their new name is a combo of names, and their new age is their combined age.
also for the hell of it, going to keep track of how many people, and how many groups there are separately (just so inheriting makes any sense in this example.)
class Person:
count = 0
def __init__(self, name, age):
self.name = name
self.age = age
self.id = make_person() # count is also the person's id in this example
def __str__(self):
return f'Name: {self.name} Age: {self.age}'
#classmethod
def make_person(cls):
cls.count += 1
return cls.count
class Group(Person):
def __init__(self, *people):
#not sure how to do this, Below Does Not Work, something like
new_name = self.make_group(people)
new_age = self.new_age(people)
self.name = new_name
self.age = new_age
super().__init__(self.new_name, self.new_age)
def make_group(self, *people):
return (' & ').join([person.name for person in People])
def new_age(self, *people):
return sum([person.age for person in people])
then you would think i could write
anne = Person('Anne', 20)
bob = Person('Bob', 20)
carl = person('Carl', 25)
couple = Group(anne, bob)
threesome = Group(anne, bob, carl)
print(couple)
print(threesome)
but this doesnt work. For some reason the group class isnt getting the people object i pass, or i'm defining it wrong...any ideas?
What you have written is that a Group is a particular type of Person. This doesn't seem quite right to me. Regardless, here is a version that will run and give the desired output:
class Person:
count = 0
def __init__(self, name, age):
self.name = name
self.age = age
self.id = Person.make_person() # count is also the person's id in this example
def __str__(self):
return f'Name: {self.name} Age: {self.age}'
#classmethod
def make_person(cls):
cls.count += 1
return cls.count
class Group(Person):
def __init__(self, *people):
#not sure how to do this, Below Does Not Work, something like
new_name = self.make_group(*people)
new_age = self.new_age(*people)
self.name = new_name
self.age = new_age
super().__init__(self.name, self.age)
def make_group(self, *people):
return (' & ').join([person.name for person in people])
def new_age(self, *people):
return sum([person.age for person in people])
anne = Person('Anne', 20)
bob = Person('Bob', 20)
carl = Person('Carl', 25)
couple = Group(anne, bob)
threesome = Group(anne, bob, carl)
print(couple)
print(threesome)
Changes from your code:
some typos with capital letters
put a * before people when passing it
take care of variable scope

Creating a class method __str__

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.

Python Pet Class

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

Python Class Pet Program

I am working on an assignment for Python Programming 157 at my school.
I need to write a class called Pet that has the following data attributes:
__name (for the name of the pet)
__animal_type (Examples: "Cat", "Dog", and "Hamster" )
__age (for the pet's age)
__height (for the pet's height)
It needs to include
set_name
get_name
I have tried like 4 times and cannot seem to get it right... any clues on getting it started?
# The Pet Program.
class PetProgram:
# The __init__ method accepts an argument for the program
# and adds it to the __pets attribute.
def __init__(self, pet):
self.__pets = pet
# The name will add to the pet attribute.
def name(self, name):
self.__pets = name
def age(self, age):
self.__pets = age
def animal(self, animal):
self.__pets = animal
def height(self, height):
self.__pets = height
# The pets_return will show you the list.
def pets_return(self):
return self.__pets
# The Pet Program.
import petsprogram
def main():
# Enter the name.
petname = input('What is the name of the pet: ')
print 'This will be added to the record.'
savings.name(petname)
# Display the list.
print petsprogram
main()
Above is my latest try...no such luck...any help? Thanks in advance...
A class is not a program, a class should model a thing, like a pet. Therefore, to start off, you should name your class appropriately.
class Pet(object): # Pet derives from the object class, always do this
Now I think you want a constructor that takes the name of the pet, and perhaps the type of pet as well, so we'll define that.
def __init__(self, pet_name, pet_type):
self.pet_name = pet_name
self.pet_type = pet_type
You also need a get and set for the name:
def get_name(self):
return self.pet_name
def set_name(self, pet_name):
self.pet_name = pet_name
To use this class, you instantiate it into an instance of the class:
puppy = Pet('Rover', 'Dog')
puppy.get_name() # prints Rover
I hope that's enough to get you going. You should read up on OOP in Python as mentioned in the comments.
First, why are you using "private" __attributes? That doesn't seem warranted.
Second, you're assigning all your properties to the same instance variable:
self.__pets = pet
self.__pets = name
self.__pets = age
self.__pets = animal
self.__pets = height
You should be using something like
def __init__(self, pet, name, age, animal, height):
self.pet = pet
self.name = name
self.age = age
self.animal = animal
self.height = height
and you should definitely read the tutorial on classes before venturing any further.
I'm not sure where the __pets binding comes into play. Your initial description doesn't say anything about that. I would not have expected an object that represents a pet, as in, a singular pet, to have an attribute that was a list of pets. I would expect something like:
class PetProgram:
def __init__(self, name ='', age=0, type='Unknown', height=0):
self.__name = name
self.__age = age
self.__animal_type = type
self.__height = height
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
I'm also not sure where the imports petprogram comes from... is that perchance what your supposed to call your module, and then the instructor has provided that as something you're supposed to run to test it?
(also, what's with all the __under_scores? is this something your teacher is encouraging?)
How does something like this look?
>>> class Pets:
def set_Name(self,name):
self.name=name
def get_Name(self):
return self.name
def set_Atype(self,atype):
self.atype=atype
def get_Atype(self):
return self.atype
def set_Age(self,age):
self.age=age
def get_Age(self):
return self.age
def set_Height(self,height):
self.height=height
def get_Height(self):
return self.height

Categories