User Tools

Site Tools


python:python_misc:oo_fundamentals_with_python

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
python:about_python:about_python_oo_fundamentals [2018/03/23 18:26] – [Class-based object-orientation] mithatpython:python_misc:oo_fundamentals_with_python [2018/08/23 17:07] – [Class-based object-orientation] mithat
Line 1: Line 1:
-====== Python Object-Orientation Fundamentals ======+====== Object-Orientation Fundamentals with Python ======
  
 ===== What you'll need to know ===== ===== What you'll need to know =====
-In what follows, we assume know basic Python programming concepts including:+In what follows, we assume you know basic Python programming concepts including:
  
   * How to create and use variables.   * How to create and use variables.
Line 37: Line 37:
  
 All these attributes, which can be defined in terms of data, collectively define the oven's state.  All these attributes, which can be defined in terms of data, collectively define the oven's state. 
 +
 ==== Behavior ==== ==== Behavior ====
  
Line 46: Line 47:
   * And so on.   * And so on.
  
-These operations are one that happen to be public-facing (i.e., operations a user can engage). There might very well also be operations that go on inside the oven to support the oven's functioning that the user will never be aware of. All these operations collectively define the oven's behavior. We call the public-facing behavior (i.e., the operations a user can engage) the oven's **interface**.+These operations are ones that happen to be public-facing (i.e., operations a user can engage). There might very well also be operations that go on inside the oven to support the oven's functioning that the user will never be aware of. All these operations collectively define the oven's behavior. We call the public-facing behavior (i.e., the operations a user can engage) the oven's **interface**.
  
 ====  Encapsulation and protection ==== ====  Encapsulation and protection ====
Line 53: Line 54:
 Along the same lines, the way I change the clock's setting is by engaging the "set current time" operation. The operation takes care of all the details of getting the data to the right place, etc. As a user, I don't need to know exactly how it does it. I only need to know what to expect from the operation. Along the same lines, the way I change the clock's setting is by engaging the "set current time" operation. The operation takes care of all the details of getting the data to the right place, etc. As a user, I don't need to know exactly how it does it. I only need to know what to expect from the operation.
  
-Ξ In fact, even if I wanted to get at the magnetron or directly change the clock's setting, I couldn't---at least not without a whole lot of pain and bother. The oven's insides are normally protected against public fiddling by screws and scary labels. But even if I manage to open it up, I would still need to know, say, where the clock module is, what its electronics parameters are, and a whole bunch of other hackery. No thanks. It's better to just use the designed-in public-facing behavior---its interface---than get a PhD in microwave oven design.+In fact, even if I wanted to get at the magnetron or directly change the clock's setting, I couldn't---at least not without a whole lot of pain and bother. The oven's insides are normally protected against public fiddling by screws and scary labels. But even if I manage to open it up, I would still need to know, say, where the clock module is, what its electronics parameters are, and a whole bunch of other hackery. No thanks. It's better to just use the designed-in public-facing behavior---its interface---than get a PhD in microwave oven design.
  
-Ξ The "not caring about how it works---I only need to know what it does" is part of **encapsulation** (literally, "to place in a capsule"). This is a key concept in object design. Keeping someone out of stuff they should not be allowed to access is called **protection** or sometimes **information hiding**.+The "not caring about how it works---I only need to know what it does" is part of **encapsulation** (literally, "to place in a capsule"). This is a key concept in object design. Keeping someone out of stuff they should not be allowed to access is called **protection** or sometimes **information hiding**.
  
 In many languages, properly hiding things the user has no business getting to is considered part of encapsulation. In many languages, properly hiding things the user has no business getting to is considered part of encapsulation.
Line 69: Line 70:
 {{:python:about_python:farberware4241-200.jpeg?nolink|}} {{:python:about_python:farberware4241-200.jpeg?nolink|}}
  
-I have a Farberware 4241 microwave oven in my office. It's small, but it gets the job done. There is a factory somewhere making these by the thousand million. They make all the Farberware 4241s from a master plan. That master plan defines what the Farberware 4241 //is//. In computing terminology, we would call that master plan a **class**. A class contains all the specifications needed to make a particular kind of object. +Because OOP models itself after real-world objects, we're going to use a real-world object to explore some more OOP concepts. 
 + 
 +I have a Farberware 4241 microwave oven in my office. It's small, but it gets the job done. There is a factory somewhere making these by the thousand million, and they make all the Farberware 4241s from a master plan. That master plan defines what the Farberware 4241 //is//. In computing terminology, we would call that master plan a **class**. A class contains all the specifications needed to make a particular kind of object. 
  
 Every Farberware 4241 begins its life identical to every other freshly-made Farberware 4241 because they were made using the same master plan. So, the one in my office that I pulled out of the box last month was identical to the one that I bought my best friend last week later because they were built from the same master plan, or, if you will, the same class. But as my best friend and I started using our ovens, the state of each changed. Note that while the behavior designed into the oven---the operations it's capable of---doesn't (and won't) change, the state of any individual oven does change over time. Every Farberware 4241 begins its life identical to every other freshly-made Farberware 4241 because they were made using the same master plan. So, the one in my office that I pulled out of the box last month was identical to the one that I bought my best friend last week later because they were built from the same master plan, or, if you will, the same class. But as my best friend and I started using our ovens, the state of each changed. Note that while the behavior designed into the oven---the operations it's capable of---doesn't (and won't) change, the state of any individual oven does change over time.
Line 88: Line 91:
  
 We are going to write a class for implementing one of these:((Picture from: "Totty Clicker - Gadgets at Play.com (UK)." Play.com (UK): DVDs, Music CDs, MP3s, Video Games, Books, Electronics & Gadgets - Free Delivery. [[http://www.play.com/Gadgets/Gadgets/4-/11566684/Totty-Clicker/Product.html?ptsl=1&ob=Price&fb=0#]] (accessed January 25, 2011).  We are going to write a class for implementing one of these:((Picture from: "Totty Clicker - Gadgets at Play.com (UK)." Play.com (UK): DVDs, Music CDs, MP3s, Video Games, Books, Electronics & Gadgets - Free Delivery. [[http://www.play.com/Gadgets/Gadgets/4-/11566684/Totty-Clicker/Product.html?ptsl=1&ob=Price&fb=0#]] (accessed January 25, 2011). 
-)) \\ {{tottycounter.jpg?234|}}+)) \\ {{..:about_python:tottycounter.jpg?234|}}
  
 In case you've never seen this bit of advanced technology before, it's a clicker-counter or tally-counter. It has two controls: a button you click to advance the counter by one and another you press to reset the count to zero. Our goal is to build one of these in software using object-orientation. In case you've never seen this bit of advanced technology before, it's a clicker-counter or tally-counter. It has two controls: a button you click to advance the counter by one and another you press to reset the count to zero. Our goal is to build one of these in software using object-orientation.
  
-Ξ One way to start building a model for a class is to start listing the public-facing behavior (or the //interface//) you want an object of that class to have. A pretty comprehensive list of the things you might do with a clicker-counter is:+One way to start building a model for a class is to start listing the public-facing behavior (or the //interface//) you want an object of that class to have. A pretty comprehensive list of the things you might do with a clicker-counter is:
  
   * //click//: makes the count increase by one.   * //click//: makes the count increase by one.
   * //reset//: sets the count to zero.   * //reset//: sets the count to zero.
  
-Next we can think about what data we'll need to keep track of the state of a clicker-counter. In this case, it's pretty simple: all we really need is one integer to store the count value.+Next we can think about what data we'll need to keep track of the state of a clicker-counter. In this case, it's pretty simple: all we really need is one integer to store the //count// value.
  
-Ξ So, a summary of what we need so far is:+So, a summary of what we need so far is:
  
   * a //click// operation   * a //click// operation
   * a //reset// operation   * a //reset// operation
-  * an integer to store the count+  * an integer to store the //count//
  
-Ξ In Python, object **attributes**, which together make up the state, are defined in special variables called **instance variables**. A class definition can include as many instance variables as it needs to store the state. In our case, we are getting off easy: the clicker-counter only needs one. The **operations** our object will be capable of, which make up behavior, are defined using **instance methods**. In Python a method is nothing more than a function defined inside a class. We call anything belonging to a class (e.g., instance variables and methods) a **member** of the class.+In Python, object **attributes**, which together make up the state, are defined in special variables called **instance variables**. A class definition can include as many instance variables as it needs to store the state. In our case, we are getting off easy: the clicker-counter only needs one. The **operations** our object will be capable of, which make up behavior, are defined using **instance methods**. In Python a method is nothing more than a function defined inside a class. We call anything belonging to a class (e.g., instance variables and methods) a **member** of the class.
  
 Class names in Python traditionally use [[http://www.c2.com/cgi/wiki?CamelCase|CamelCase]] with the first letter capitalized. Class names in Python traditionally use [[http://www.c2.com/cgi/wiki?CamelCase|CamelCase]] with the first letter capitalized.
Line 125: Line 128:
 </code> </code>
  
-Class definitions follow the same header/suite pattern for compound statements you've seen before with control flow statements and function definitions. The keyword ''class'' in the header declares that what follows is a class definition. The 'ClickerCounter' identifier is the name of our class. And the parenthesis are there for implementing an advanced feature that we'll not tackle here.+Class definitions follow the same header/suite pattern for compound statements you've seen before with control flow statements and function definitions. The keyword ''class'' in the header declares that what follows is a class definition. The ''ClickerCounter'' identifier is the name of our class. The parenthesis that follow the name of the class are there for implementing an advanced feature that we'll not tackle here.
  
-The suite of the class definition nests additional compound statements, in this case a set of function definitions---the instance methods.+The suite of the class definition nests additional compound statementsfunction definitions that make up the instance methods.
  
 In this class definition, we define three instance methods: ''%%__init__(self)%%'', ''click(self)'', and ''reset(self)''. These methods will belong to objects created with this class; they won't have any meaning outside of this context. In this class definition, we define three instance methods: ''%%__init__(self)%%'', ''click(self)'', and ''reset(self)''. These methods will belong to objects created with this class; they won't have any meaning outside of this context.
Line 134: Line 137:
  
 <WRAP center round tip 80%> <WRAP center round tip 80%>
-A common error is to forget to use ''self'' as the first parameter in an instance method definition. Another common error is to forget to use ''self'' to qualify the names of instance variables. Things will go wonky if you do either of these.+A common error is to forget to use ''self'' as the first parameter in an instance method definition. Another common error is to forget to use ''self'' to qualify the names of instance variables inside instance methods. Things won'go as expected if you do either of these.
 </WRAP> </WRAP>
  
-=== ✘ The __init__ method and instance variables ===+=== The __init__ method and instance variables ===
  
 In our class definition, the roles of the ''click()'' and ''reset()'' methods are probably self-evident: ''click()'' increments the object's ''count'' member variable by one, and ''reset()'' resets it to zero. In our class definition, the roles of the ''click()'' and ''reset()'' methods are probably self-evident: ''click()'' increments the object's ''count'' member variable by one, and ''reset()'' resets it to zero.
Line 149: Line 152:
 </WRAP> </WRAP>
  
------------------------------------------- +==== Instantiation and use ====
------------------------------------------- +
- +
-==== Ξ Instantiation and use ====+
  
 Once you have a definition for a class, invoking the name of the class with a pair of parenthesis will instantiate an object from that class. Once you have a definition for a class, invoking the name of the class with a pair of parenthesis will instantiate an object from that class.
Line 176: Line 176:
 you can also see that it's an object and the memory location where it's stored. you can also see that it's an object and the memory location where it's stored.
  
-Ξ Stuff like the above is useful for debugging. Most of the time, once you instantiate objects, you just start to use them. So let's instantiate a clicker, click it three times, and print the resulting ''count'' value.+Stuff like the above is useful for debugging. Most of the time, once you instantiate objects, you just start to use them. So let's instantiate a clicker, click it three times, and print the resulting ''count'' value.
  
 <code python> <code python>
Line 216: Line 216:
 Python's inner workings manage the fist parameter automatically and implicitly. Python's inner workings manage the fist parameter automatically and implicitly.
  
-==== ♠ Parameterized constructors and methods ====+==== Parameterized constructors and methods ====
 The ''%%__init__%%'' constructor is just a special method, and a method is just a function attached to an object. So, there's nothing keeping you from adding parameters to a constructor if needed. Let's modify the ''ClickerCounter'' class so it has a count limit: when the limit is reached, the counter will automatically reset. Furthermore, we will set this upper limit with a parameter in the constructor. The ''%%__init__%%'' constructor is just a special method, and a method is just a function attached to an object. So, there's nothing keeping you from adding parameters to a constructor if needed. Let's modify the ''ClickerCounter'' class so it has a count limit: when the limit is reached, the counter will automatically reset. Furthermore, we will set this upper limit with a parameter in the constructor.
  
-Ξ First we need to redefine the constructor to take a limit parameter and set an instance variable to that value:+First we need to redefine the constructor to take a limit parameter and set an instance variable to that value:
  
 <code python> <code python>
Line 227: Line 227:
 </code> </code>
  
-Ξ Next we need to modify the ''click'' method so it wraps around when the limit is reached:+Next we need to modify the ''click'' method so it wraps around when the limit is reached:
  
 <code python> <code python>
Line 237: Line 237:
 </code> </code>
  
-⇒ This yields:+This yields:
 <code python> <code python>
 class ClickerCounter(): class ClickerCounter():
Line 265: Line 265:
 </code> </code>
  
-♠ General methods can also be parameterized. The process is identical to using parameters with constructors. +General methods can also be parameterized. The process is identical to using parameters with constructors.
- +
--------------------------------------------------------- +
---------------------------------------------------------+
  
 ==== Next steps ==== ==== Next steps ====
python/python_misc/oo_fundamentals_with_python.txt · Last modified: 2018/11/30 18:45 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki