Python Forum
Help me improve my code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help me improve my code
#1
Hi.
I'm new to programming and Python, but I do enjoy learning as much as I can.
I started play around with classes in Python and get the most basic stuff.
But I would like some help to get the code even better. And more readable.

Most variables and words are in swedish.
My code first creates vehicles and one motorcycle.
Then I can do stuff to theese class objects.
I can get the miltal (mileage), inköpspris (buy-price).
I can also calculate the säljpris (sell-price) and service (repairs) in separate functions.

class fordon():

    
    hjul = 2        #Standardvariabel
    
    def __init__(self, märke, modell, inköpspris, miltal):
        
        self.märke = märke
        self.modell = modell
        self.inköpspris = inköpspris
        self.miltal = miltal

class bil(fordon):
    
    hjul = 4
    def spec(self, doors, hp):
        self.doors = doors
        self.hp = hp

class mc(fordon):

    
    def spec(self, hp):
        self.hp = hp

#Funktion som räknar ut säljpris
def sälj(object):
    
    if object.miltal > 3000:
        return object.inköpspris * 1.10
    else:
        return object.inköpspris * 1.20

def service(object):
    
    if object.miltal > 12000:
        return '{} {}{}'.format(object.märke, object.modell, " behöver service")
    else:
        return '{} {}{}'.format(object.märke, object.modell, " behöver inte service än")



bil_1 = bil("Audi", "A8", 10000, 4000)
mc_1 = mc("Yamaha", "R1", 10000, 2000)
bil_2 = bil("Volvo", "XC70", 20000, 3342)
All the help I can get would be worth alot. Wink
Reply
#2
Hello and welcome to Python and our forums! Thanks for posting your code (and using code tags) Thumbs Up I moved the thread to Completed Scripts/Snippets subforum, as this is the place for posting working code and code reviews. Wink
Reply
#3
(Jan-26-2018, 08:03 AM)Emagii Wrote: I would like some help to get the code even better.
Class code doesn't need to be perfect. In python, it needs to be malleable. Whether it is good code or not largely depends on what you want to do with these classes.

You could make sälj() and service() methods of class fordon.

It would be better if you adopt the usual convention to capitalize class names, so Fordon, Bil, Mc.
Reply
#4
Thanks for replying Gribouillis

(Jan-26-2018, 08:50 AM)Gribouillis Wrote: You could make sälj() and service() methods of class fordon.

It would be better if you adopt the usual convention to capitalize class names, so Fordon, Bil, Mc.

I have changed this now and it looks better.
I did put the functions sälj() and service() in the class Fordon before. But did get some errors. Reason was probably that I wrote some mistakes.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020