#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    2

    Stuck with question on Class and function


    Hi,
    done remaining work less the following question. Stuck on it for sometime now, unable to figure it out. Any guidance is appreciated. Thank you.

    Question:
    Idea is to create a class containing objects and be able to change the value of the variable using the following 3 functions.

    a) To create a class containing 3x variables representing any properties.
    b) Use the following 3 functions
    getitem1() - to use return key to return value of item 1
    setitem1() - to allow new value to be specified for item 1 additional parameter to accept input required.
    printcar() - to print value of variable for the object.
    c) create 1x object of the class and call each get/set methods once for the object created.
    d) call printcar() to check if the method is working.

    My working:

    Code:
    class car_parts: # class created with 3 variables and properties
        wheels = 4
        brand = 'Honda'
        fuel = 'petrol'
    
        def printcar(self):
            print self.wheels 
    
        def getitem1(self): # Not sure where I should call it
            return self.wheels
    
        def setitem1(self, wheels):
            self.wheels = wheels
    
    F1 = raw_input('Please enter no. of wheels: ')
    
    setitem1(F1)# error  
    
    car_parts_1 = car_parts()
    car_parts_1.wheels = 10 # changing value and it works. But unable to figure out how to fit it into a fucntion 
    car_parts_1.printcar()
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    25
    Rep Power
    0
    Well, here's a fixed up version of your code:
    Code:
    class CarParts(object): # notice CapWords and object inheritance
        def __init__(self): # always use __init__ functions for classes
            self.wheels = 4 # and self. in front of local variables of that class
            self.brand = 'Honda' 
            self.fuel = 'petrol' 
    
        def print_car(self):
            print self.wheels
            print self.brand
            print self.fuel
    
        def get_item(self):
            return self.wheels
            return self.brand
            return self.fuel
    
        def set_item(self, wheels, brand, fuel):
            self.wheels = wheels # this part you did ok
            self.brand = brand
            self.fuel = fuel
    
    wheels = raw_input('Please enter no. of wheels: ')
    brand = raw_input('Please enter the car brand: ')
    fuel = raw_input('Please enter the fuel that the car uses: ')
    
    car_parts = CarParts(wheels, brand, fuel)
    
    car_parts.print_car()
    car_parts.set_item(wheels, brand, fuel)
    car_parts.print_car() # test if the stuff really changes
    Also, class names should always be CapWords and functions are lowercase with underscores to separate words, as refered by The Style Guide for Python Code(search it up for reference).
    The object thing is necessary in case you are writing in python2.x - object represents that it is a new-style class, which has some improvements over the classic classes, which are implied if there is no object inheritance for a class in python2.x.
    And about the error that was showing, it was there because that function is a part of a class, hence it needs car_parts.set_item.
    You could also put all the raw_input() stuff inside the set_item function, so you only have to type it in if you want.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    2
    Thanks for reply. I am not familiar with __init__(self). I'm currently looking it up.

    Also when the codes are executed, error message appears at the end saying __init__() takes exactly 1 argument ( 4 given). Do advice, thanks.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    Originally Posted by Lucantrop
    Cute!
    Code:
        def get_item(self):
            return self.wheels
            return self.brand
            return self.fuel
    Code:
    import pprint
    
    class generic:
    
        defaults = {}
    
        def __init__(self,**kwargs):
            self.__dict__.update(self.__class__.defaults)
            self.__dict__.update(kwargs)
    
        def __repr__(self):
            Class = self.__class__
            d = {key:self.__dict__[key] for key in Class.defaults.keys()}
            return '{:s}(**{:s})'.format(Class.__name__,pprint.pformat(d))
    
        def __str__(self):
            d = {key:value for (key,value,) in self.__dict__.items() if not key.startswith('__')}
            return pprint.pformat(d)
    
    EXAMPLE = '''
        $ python p.py
        {'manufacturer': 'Honda', 'thelman_wire': 'corroded', 'tires': 4, 'windows': 6}
        Honda
    '''
    
    CAR = generic(manufacturer='Honda',tires=4,thelman_wire='corroded')
    CAR.windows = 6
    print(CAR)
    print(CAR.manufacturer)
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    25
    Rep Power
    0
    Originally Posted by keshk
    Thanks for reply. I am not familiar with __init__(self). I'm currently looking it up.

    Also when the codes are executed, error message appears at the end saying __init__() takes exactly 1 argument ( 4 given). Do advice, thanks.
    Oh yeah, that's because i forgot to change the car_parts = CarParts(wheels, brand, fuel) to:
    Code:
    car_parts = CarParts()
    @b49P23TIvg
    Well damn, you're good :D I'm new to still new to programming btw, so I pretty much don't understand a thing you did there. I'm going to have to research that stuff first thing in the morning.
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    54
    Rep Power
    2
    Thanks for reply.

    @b49P23TIvg Still working on understanding your codes. Need some time.

    I made some slight modifications based on the suggestions and the codes are working now. One slight problem. For the function:

    Code:
    def sayHello_get(self):
            print ' '
            print 'Testing if get method works.'
            print '----------------------------'
            print 'Details on new goat.'
            print str(Goat_1.get_horns()) + ' horns.'
            print str(Goat_1.get_legs()) + ' legs.'
            print str(Goat_1.get_teeth()) + ' teeth.'
    I have straight away inserted Goat_1 in it which I am sure is wrong. I want it to be able to accept information and print differently if I enter a Goat_2, Goat_3 and so on with different values. My entire code is below. Please advice. Thanks for help.

    Code:
    class Goat():
        horns = 2
        legs = 4
        teeth = 10
    
        def get_horns(self):
            return self.horns
    
        def get_legs(self):
            return self.legs
    
        def get_teeth(self):
            return self.teeth
    
        def set_horns(self, horns):
            self.horns = horns
    
        def set_legs(self, legs):
            self.legs = legs
    
        def set_teeth(self, teeth):    
            self.teeth = teeth
    
        def sayHello_get(self):
            print ' '
            print 'Testing if get method works.'
            print '----------------------------'
            print 'Details on new goat.'
            print str(Goat_1.get_horns()) + ' horns.'
            print str(Goat_1.get_legs()) + ' legs.'
            print str(Goat_1.get_teeth()) + ' teeth.'
    
        def sayHello_set(self):
            print 'Testing if set method works.'
            print '----------------------------'
            print 'This goat has ' + self.horns + ' horns, ' + self.legs + ' legs and ' + self.teeth + ' teeth.'
    
    
    
    # Main Program
    new_Horns = raw_input('Please enter no. of horns for your goat: ')
    new_Legs = raw_input('Please enter no. of legs for your goat: ')
    new_Teeth = raw_input('Please enter no. of teeth for your goat: ')
    
    Goat_1 = Goat()
    Goat_2 = Goat()
    
    Goat_1.set_horns(new_Horns)
    Goat_1.set_legs(new_Legs)
    Goat_1.set_teeth(new_Teeth)
    
    print ' ' 
    Goat_1.sayHello_set()
    print ' '
    Goat_1.sayHello_get() 
    Goat_2.sayHello_get()
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    25
    Rep Power
    0
    Code:
    class Goat(object):
        self.horns = 2
        self.legs = 4
        self.teeth = 10
    .
    .
    .
    def sayHello_get(self):
            print '\nTesting if get method works.' # \n - new line character, google python escape sequences
            print '----------------------------'
            print 'Details on new goat.'
            print str(self.get_horns()) + ' horns.'
            print str(self.get_legs()) + ' legs.'
            print str(self.get_teeth()) + ' teeth.'
    
    goat1 = Goat()
    goat2 = Goat()
    
    .
    .
    .
    Inside a class, every (future) instance of it is referred to as self - self.get_horns() etc. Search for Python documentation on classes, I think they pretty much got it right. Good luck
  14. #8
  15. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    608
    Rep Power
    65
    Here is the meat ...
    Code:
    class Box:
        '''
        class Box with methods surface and volume
        self is the instance of a particular box
        with given data length, width, and height
        self. prefix also passes instance data to methods
        '''
        def __init__(self, length, width, height):
            self.length = length
            self.width = width
            self.height = height
    
        def volume(self):
            '''
            a method starts with argument self
            this method calculates the volume of a box instance
            '''
            return self.length * self.width * self.height
    
        def surface(self):
            '''
            this method calculates the surface area of a box instance
            '''
            area1 = (self.length * self.width)
            area2 = (self.length * self.height)
            area3 = (self.width * self.height)
            return  2 * area1 + 2 * area2 + 2 * area3
    
    
    # supply dimensions length, width, height of instance box_a
    # as arguments of class __init__()
    box_a = Box(10, 1, 1)
    
    # make another box instance box_b with different dimensions
    box_b = Box(10, 2, 1)
    
    print("box_a volume = {}".format(box_a.volume()))
    print("box_b volume = {}".format(box_b.volume()))
    print('-'*20)
    print("box_a surface = {}".format(box_a.surface()))
    print("box_b surface = {}".format(box_b.surface()))
    
    '''my result -->
    box_a volume = 10
    box_b volume = 20
    --------------------
    box_a surface = 42
    box_b surface = 64
    '''

    Comments on this post

    • Lucantrop agrees : That's a nice explanation :)
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0

    Well..


    Sorry to go back to an old post, just a bit perplexed by this. I done the code above i copied the refined version by Lucandrop, however it still doesn't work for me? I even created my own on the basis of the same principles but the first 'self' in my method print_info is a error?

    Code:
    class VehicleInfo (object):  
    
      def _init_(self):
         self.vehicleid = 1
         self.registration = 'NX09DUO'
         self.size = '14T'
         self.type1 = 'Rigid'  # Reason for it being type1 is that python already uses 'type'
         self.lservice = 12/12/12
         self.serviced = 13/12/13
         self.ldefect = 'Rear tyre'
         self.ldriver = 'Paul Potts'
         self.mileage = 122200
         self.fleet = 'Thurrork'
    
      def print_info(self):
         print self.vehicleid 
         print self.registration 
         print self.size 
         print self.type1 
         print self.lservice 
         print self.serviced 
         print self.ldefect 
         print self.ldriver 
         print self.mileage 
         print self.fleet
    
      def get_info(self):
         return self.vehicleid 
         return self.registration 
         return self.size 
         return self.type1 
         return self.lservice 
         return self.serviced 
         return self.ldefect 
         return self.ldriver 
         return self.mileage 
         return self.fleet
    
        def set_item (self, vehicleid, registration, size, type1,
                      lservice, serviced, ldefect, ldriver, mileage, fleet):
    
         self.vehicleid = vehicleid
         self.registration = registration
         self.size = size
         self.type1 = type1
         self.lservice = lservice
         self.serviced = serviced
         self.ldefect = ldefect
         self.ldriver = ldriver
         self.mileage = mileage
         self.fleet = fleet
    
         vehicleid = raw_input ('Please enter Vehicle ID number: ')
         registration = raw_input ('Please enter Vehicle Registration: ')
         size = raw_input ('Please enter Vehicle Size: ')
         type1 = raw_input ('Please enter Vehicle type: ')
         lservice = raw_input ('Please enter Vehicles last service date: ')
         serviced = raw_input ('Please enter When Service is due: ')
         ldefect = raw_input ('Please enter last known defect: ')
         ldriver = raw_input ('Please enter last driver of the vehicle: ')
         mileage = raw_input ('Please enter vehicle milage ')
         fleet = raw_input ('Please enter the fleet vehicle is from ')
    
    vehicle_info = VehicleInfo()
    
    vehicle_info.print_info()
    vehicle_info.set_item(vehicleid, registration, size, type1, lservice, serviced,
                           ldefect, ldriver, mileage, fleet)
    vehicle_info.print_info()
    Thank you for your time to review this, just hoping for some pointers. I'm new to Python
  18. #10
  19. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    You must follow the indentation rules for python to accept your program. def set_item has to agree with indentation of def_get_info.
    Code:
      def get_info(self):
        def set_item (self, vehicl
    There are also important differences between
    Code:
    __init__
    _init_
    [code]Code tags[/code] are essential for python code and Makefiles!
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0
    Code:
     def print_info(self):
         print self.vehicleid # Error is at this 'self' 
         print self.registration 
         print self.size 
         print self.type1 
         print self.lservice 
         print self.serviced 
         print self.ldefect 
         print self.ldriver 
         print self.mileage 
         print self.fleet
    I made the changes in your previous comment but this is still the issue.
  22. #12
  23. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    I think you did not change
    Code:
    _init_
    #to
    __init__
    It was a subtle comment.
    [code]Code tags[/code] are essential for python code and Makefiles!
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    25
    Rep Power
    0
    Either that or the indentation, make sure you have 4 spaces per indent. Also, the raw_input stuff shouldn't be indented, and the stuff below def set_item(...): should be. That and __init__(self): will definitely fix it.

IMN logo majestic logo threadwatch logo seochat tools logo