Hello,

i'm learning object -oriented programming,

I was told to create a program that once the class had been designed, to create an object of the class and prompt the user to enter the name, type, and age of his or her pet. The data should be stored in the object. The object acessor methods to retrieve the pet's name, type and age and display this data on the screen.

here is what i have, but i'm getting a error. any help will be much appreciate

class Pet:
    def __init__(self,petName,petAge,myPet):
        self.__myPet= newPet

    def setName(self,n):
        self.__setName=n
        
    def setType (self, t):
        self.__setType=t
        
    def setAge(self, a):
        self.__setAge= a
        
    def getName (self):
        return self.__Name
    
    def getType (self):
        return self.__Type
    
    def getAge (self):
        return self.__Age
    
def main():
    myPet.setName(petName)
    petName= input= ('Please enter your pets name')
    myPet.setType(petType)
    petType= input= ('Please enter your pets type.ie:Dog,Cat,Bird,Reptile')
    myPet.setAge(petAge)
    petAge= raw_input= ('Please enter your pets age')      

    print myPet.getName()
    print myPet.getType()
    print myPet.getAge()

main()

Your def__init__ constructor take args that are no refered anywhere in your code.

Fix that. Use that for basic initializing of your variables.
;)

I think you need also need to upgrade the mind of your instructor, give him print of http://dirtsimple.org/2004/12/python-is-not-java.html as present and ask him to stop acting against Python-do.

Getters and setters are evil. Evil, evil, I say! Python objects are not Java beans. Do not write getters and setters. This is what the 'property' built-in is for. And do not take that to mean that you should write getters and setters, and then wrap them in 'property'. That means that until you prove that you need anything more than a simple attribute access, don't write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well.

Sorry, could not resist to simplify (and yes it does not check anything, but as long as you test the input properly, you get the expected results):

class Pet(object):
    def __init__(self,**kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        return ('Pet(' +
                ', '.join('%s=%r' % (name, item)
                         for name,item in self.__dict__.items()) +
                ')'  )
    
def main():
    prompt = 'Please enter your pets %s: '
    mypet = Pet(name=raw_input(prompt % 'name'),
                type=int(raw_input(prompt % 'type')),
                age=raw_input(prompt % 'age'))

    print mypet

main()

""" Output:
>>> 
Please enter your pets name: Miso
Please enter your pets type: cat
Please enter your pets age: 5
Pet(age=5, type='cat', name='Miso')
"""

(Error handling missing)

Nice effort! I decided to rewrite your code to make a it bit shorter (it's a little long winded having lots of seperate functions for each bit of data). My code does look fairly long, but I have left comments, lots of whitespace, and a demo to prove that it works. I've commented the code so it's "self.explanatory" :)

#need for system commands
import os


#pet class
class Pet:

	#__init__ function
	#compressed setting all data into this functino
	def __init__(self, name, type, age):
		#take data from args and give to class variables
		self.name = name
		self.type = type
		self.age = age


	#function to return all the data
	def getData(self):
		#take from class variables
		return (self.name, self.type, self.age)


#main
def main():

	#request input
	print 'Enter name (string)'
	#input
	name = str(raw_input())

	#repeat
	print 'Enter type (string)'
	type = str(raw_input())

	#repeat with newline for whitespace
	print 'Enter age (int)', "\n"
	age = int(raw_input())

	#make new pet instance
	myPet = Pet(name, type, age),

	#get the data
	data = myPet.getData()

	#variable for while loop condition
	i=0;
	#loop
	while i < 3:
		#will print each bit of data on new line
		print data[i]
		#increment loop variable
		i+=1

	#pause so we can read the data
	os.system("pause")

#call the main
main()

Please upvote if it helped and solved if it fixed your problem :)

PS. Please include the error message in your post next time 'cos it helps us out a little. Thanks :)

My post edit time finished the int() is wrong line, I added it at last moment. It should of course be around age:

class Pet(object):
    def __init__(self,**kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        return ('Pet(' +
                ', '.join('%s=%r' % (name, item)
                         for name,item in self.__dict__.items()) +
                ')'  )
    
def main():
    prompt = 'Please enter your pets %s: '
    mypet = Pet(name=raw_input(prompt % 'name'),
                type=raw_input(prompt % 'type'),
                age=int(raw_input(prompt % 'age'))
                )

    print mypet

main()

""" Output:
>>> 
Please enter your pets name: Miso
Please enter your pets type: cat
Please enter your pets age: 5
Pet(age=5, type='cat', name='Miso')
"""

Little safer version:

class Pet(object):
    attribs = ('name','type','age')
    def __init__(self,**kwargs):
        if all(arg in self.attribs for arg in kwargs.keys()):
            self.__dict__.update(kwargs)
        else:
            raise ValueError('Incorrect pet attibute error')

    def __repr__(self):
        return ('Pet(' +
                ', '.join('%s=%r' % (name, item)
                         for name,item in self.__dict__.items()) +
                ')'  )
    
def main():
    prompt = 'Please enter your pets %s: '
    mypet = Pet(name=raw_input(prompt % 'name'),
                type=raw_input(prompt % 'type'),
                age=int(raw_input(prompt % 'age'))
                )

    print mypet
    print Pet(profession = 'Java teacher')

main()

""" Output:
Please enter your pets name: Miso
Please enter your pets type: cat
Please enter your pets age: 4
Pet(age=4, type='cat', name='Miso')

Traceback (most recent call last):
  File "J:\test\obj_wrong.py", line 25, in <module>
    main()
  File "J:\test\obj_wrong.py", line 23, in main
    print Pet(profession = 'Java teacher')
  File "J:\test\obj_wrong.py", line 7, in __init__
    raise ValueError('Incorrect pet attibute error')
ValueError: Incorrect pet attibute error
"""

And yes, in Python we raise Errors instead of silence them.

#repeat
	print 'Enter type (string)'
	type = str(raw_input())

"type" is reserved by Python as a function name that returns the type of an object; a string, class, integer, etc. Use "category" or some other name that is less confusing. Also, raw_input returns a string so type casting to string is not necessary. And Python is not C, so the use of an orphaned call to main() in the body is not necessary and also confusing. It should be obvious which statements are automatically executed when the program file is executed ("readability counts" and "explicit is better than implicit"). An introduction to forming classes can be found here.

Nice link, but check response to my post in StackOverflow about 'camelCase' names:
doesPythonLikeCamels

Still, very clean style with this minor exception.

I used type in my code and I didn't get any errors and it worked fine :/ I have 2.6.4 so it may be later/earlier implementation. Yeah I think Tonyjv's code is better :L

thank you to everyone for their replys ..

here was the rules for such program.

Design a class named Pet, which should have the following fields.

name:
type:
age

The pet class should also have the following methods.

setName
setType
setAge
getName
getType
getAge

-------------

tonyjv : very true, but that what the teahcer wants to see.

SgtMe: Your code give me the following error

Traceback (most recent call last):
  File "C:/Users/ORLANDO/Desktop/pet.py", line 36, in <module>
    main()
  File "C:/Users/ORLANDO/Desktop/pet.py", line 29, in main
    data = myPet.getData()
AttributeError: 'tuple' object has no attribute 'getData'

OK, this change should satisfy the requirements:

import functools


class Pet(object):
    attribs = ('name','type','age')

    def __init__(self,**kwargs):
        if all(arg in self.attribs for arg in kwargs.keys()):
            self.__dict__.update(kwargs)
        else:
            raise ValueError('Incorrect pet attribute error: %s' % ', '.join(kwargs.keys()))
        for name, func in ('set%s', setattr), ('get%s', getattr):
            for attr in self.attribs:
                setattr(self, name % attr.title(), functools.partial(func, self, attr))

    def __str__(self):
        return ('Pet(' +
               ', '.join('%s=%r' % (name, item)
                         for name, item in self.__dict__.items() if 'functools' not in str(item)) +
               ')'  )
    
def main():
    prompt = 'Please enter your pets %s: '
    mypet = Pet(name=raw_input(prompt % 'name'),
                type=raw_input(prompt % 'type'),
                age=int(raw_input(prompt % 'age'))
                )

    print mypet
    mypet.setType('dog')
    print mypet
    print 'Pets age is: %i' % mypet.getAge()
    try:
        print Pet(name = 'Nice teacher', profession = 'Java teacher')
    except ValueError as e:
        print e
main()

""" Output:
Please enter your pets name: Miso
Please enter your pets type: cat
Please enter your pets age: 6
Pet(name='Miso', age=6, type='cat')
Pet(name='Miso', age=6, type='dog')
Pets age is: 6
Incorrect pet attribute error: profession, name
"""

tonyjv : thank you very much for your help. but your code is a little too advance for me to understand, can you please look at "SgtMe" and tell me where is the error.

his code is a little more simple for me.

One line has comma at end -> tuple value.

thank you guys, i got it to work.

Yeah sorry about that! I must have done something funny somewhere 'cos it worked fine at one point. I must have changed something before I posted it! Sorry :/ Please could you upvote my post (the one with the code) seeing as it helped you out and mark the thread as solved. Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.