# First we'll do the basic function things, and then we'll build on the idea # to expand to a more useful function # When using functions we PASS IN information using parameters and RETURN # a value - the variables inside the function are LOCAL to that function # and don't exist outside of it (in fact they cease to exist as soon as # the end of the function is reached and will be created anew each time # the function is called). There are exceptions, but this is the general way # we use functions. def box_volume(width,height,depth): # width, height and depth are parameters volume = width * height * depth # Here we create a local variable... return volume # ... and return it # We didn't actually need to create a "volume", we could have just done: return width * height * depth # Also note that this second "return" will never be reached because the # function exits as soon as return is called (the first time) # Then to use this function, we can do this: print "Volume of box dimensions 1 * 2 * 3 is {}".format(box_volume( 1,2,3 ) ) # Of course we can store the value rather than printing it directly: myresult = box_volume(2,3,4) print "Volume of box dimensions 2 * 3 * 4 is {}".format( myresult ) # This is all well and good, but what if we want to store these box dimensions # so they can be used by different functions all operating on the same actual # variables? That's what classes are for! In actual fact everything in python # is a class (what you think of as variables are actually INSTANCES of a class), # so by creating a variable you are actually using classes already! # An example of this is where I have used .format() which is a FUNCTION MEMBER # of the STRING LITERAL class. # What we want to do here is create a class that represents our data type, # a Box (cuboid technically). # Lets expand this idea to use a class. Before we do anything, we need to # define the class itself (whereas integers, strings, etc are defined for you): class Box: # A class has a special function called a CONSTRUCTOR - this is a function # that is automatically called when we instantiate the class, and is used # to declare and initialise all the variables we want to use in the class. # In python specifically this is the __init__ function: def __init__(self, w=1, h=1, d=1): # Note that we have set default values for w, h and d here - these 1 # values are used if we instantiate the class without specifying these # parameters - if we didn't have the =1 bit we would get an error if we # didn't provide these parameters when we instantiated the class. # The first parameter for a FUNCTION MEMBER (which is what we call # functions belonging to a class) in python is always "self" - this # gives us a reference to the instance itself, and it is filled in # for us by python - you'll notice later that we don't ever specify this # parameter and behave as if it doesn't exist outside of the class # definition itself - more on that later. # Now we need to define variables that are local to the class instance # itself: self.width = w self.height = h self.depth = d # Here is the end of this function member; note that w, h and d will # cease to exist but width, height and depth won't because they are # DATA MEMBERS of the class - again, more on this in a minute def set_dimensions(self,w,h,d): # This isn't strictly necessary, but as an example we'll create this # function to set the class' width, height and depth data members all # in one go self.width = w self.height = h self.depth = d def get_volume(self): # Again, self is always required in a function member - this function # would be called with no arguments at all. return self.width * self.height * self.depth # There we have our simple class. In order to use it, we need to instantiate it. # In order to create an instance (ie variable) of this new class (data type) we # have defined. It may be easier to consider the way that literals work - in # python the following two statements are identical: x = 1 # the class here is implicit because python knows that the literal 1 refers to an integer x = int(1) # here we actually tell python to create a new instance of the int class # We'll create two instances of Box. __init__(w,h,d) will automatically be # called here - notice how we don't specify the first parameter (self): box1 = Box(1,2,3) # Now we'll create the second box: box2 = Box(2,3,4) # We can call the get_volume() function of each box: print "box1 has a volume of {}".format( box1.get_volume() ) # Just like any function, we can also store the result in a variable: myvolume = box2.get_volume() print "box2 has a volume of {}".format( myvolume) # We can set the values using the function we made to do so: box2.set_dimensions( 2,2,2 ) # And you can see from this that the values have been stored: print "box2 now has a volume of {}".format( box2.get_volume() ) # We can also access the data members directly - here we'll just set the width: box1.width=10 print "box1's new dimensions are {} * {} * {}".format( box1.width, box1.height, box1.depth) # And again those new values are stored as can be seen by the new volume: print "box1's new volume is {}".format( box1.get_volume() ) # Now lets change box2 again - one of the nice things about python is # the loose typing (thanks to everything being a class) so we can just # as easily specify a float value even though we used an integer when we # designed the class: box2.width = box2.height = box2.depth = 2.5 # We can access the data members just like any other variable: print "box2 is {} * {} * {} which is a volume of {}".format( box2.width, box2.height, box2.depth, box2.get_volume() ) # Hopefully this begins to paint the picture of why doing things with # classes is much more useful. # Have a play about - once you're happy using the basics of classes like this # you can move on to looking at inheritence and (big word ahoy) polymorphism! # Enjoy :)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question