[Tutor] Cobra
Peter Dilley posted these links on the python-list a few hours ago. Cobra looks VERY interesting to me. Comparison to Python: http://cobra-language.com/docs/python/ Main Page: http://cobra-language.com/ Article that first caught my eye regarding Cobra: http://www.computerworld.com.au/index.php/id;342684174;fp;16;fpid;1 Dick Moores ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
There's a couple of errors in here that no one has addressed yet because the question was geared towards programming style... So now I will address them. Or undress them, I suppose. ;-) > #!/user/bin/python > """ >>From the testing laboratory of: > b h a a l u u at g m a i l dot c o m > 2008-02-07 > """ > > import time > > CS = "\n"*50 This is okay, but it is a little more intuitive to make this def clrscr(): print "\n"*50 so that you can say clrscr() because clearing the screen is an action, not a thing that you would normally think of printing. The point of python is to make programming easier for humans. You defeat it's greatest power by not using it in a style that takes advantage of it's ability to mimic the real world. actions usually indicate functions. (This is definitely a style thing. I'm not trying to start an argument) > class TestClass1(object): >""" please give me a better name""" >def __init__(self): >"""please document me""" >self.name = "" >self.answer = "" >self.strength = 20 >self.wealth = 45 >self.light = 0 >self.tally = 0 As mentioned before, data in class should be related to one real (or abstract) object, not just a container for random data. > def main(): >tc1 = TestClass1() # instance >tc1.__init__() # invoke method >print CS >N1 = tc1.name >N1 = raw_input(" WHAT IS YOUR NAME, EXPLORER? ") This is pointless. When you assign the value of tc1.name (which is "") you immediately overwrite it when you say N1 = raw_input(...) What you are trying to accomplish without grokking assignment is this. tc1.name = raw_input("What is your name, explorer?") ># main game loop >while True: >print CS >print (" %s, YOUR STRENGTH IS %d") % (N1, tc1.strength) Earlier you set N1, but not tc1.name. Either use one or the other. >print (" YOU HAVE $%d") % tc1.wealth >if tc1.light == 0: Can be if tc1.light: print("The light's on, but no one's home") else: print("It is too dark to see anything") >print (" IT IS TOO DARK TO SEE ANYTHING") >else: >print (" THE LIGHT'S ON, BUT NO ONE'S HOME") >print >print >A = tc1.answer Again, the same problem with tc1.name. Why are you bothering with A? Please realize that you can assign directly tc1.answer = raw_input(...) and just use the one variable. This is not C, but Python. >A = raw_input(" WHAT DO YOU WANT TO DO? [Q|L]: ") # main game > prompt >if A.upper() == "Q": >break >if A.upper() == "L": >light = raw_input(" LIGHT? [0|1]: ") # turn the light on and > off >if light == 0 and tc1.light == 0: What?!? What is the deal? Do you have two different lights? No... then using two different light variables does not make sense. Also, the variable 'light' will never be == 0 unless you hit enter without entering anything because raw_input returns a string. "0" != 0 >print (" THE LIGHT IS OFF") I see. You have two seperate variables so that you can determine whether the light was off previously. In which case, I suggest you change the variable to a more intuitive name, such as 'chosen' or something. To test whether the light was on before or not, you should have a method of the class islighton() because you are performing an action. Checking to see whether the light is on. If this doesn't make sense to you, consider that often attributes of a class are not directly accessed. There are even special things called properties that define get and set methods of classes... Um, disregard that. Too much info. :-) >time.sleep(2) >if tc1.wealth <= 0: You have put this wealth check after the changing of the light. So it is possible that someone can change the light after they already have no money. >print >print (" YOU HAVE NO MONEY") >time.sleep(2) >else: >tc1.light = int(light) Good. You just didn't think of int() in the if check. btw, you aren't going to tell anyone when they turn the light on? >tc1.wealth -= 15 >else: >print (" INVALID CHOICE") >time.sleep(2) >tc1.tally += 1 >tc1.strength -= 5 >if tc1.strength <= 0: >print (" YOU DIED") >time.sleep(2) >break >print >print (" Final Score:") >print ("Tally: %d") % tc1.tally >print (" Wealth: $%d") % tc1.wealth >print (" Strength: %d") % tc1.strength > > if __name__ == "__main__": >main() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Anyone fancy giving me some tips and an expert opinion??
Damian Archer wrote: > # User inputs numbers to compare, z is for the index counter > x = input("Enter a number between 1 and 0: ") > y = input("Enter a second number between 1 and 0: ") We generally discourage the use of input(), it is (arguably) a security hole - http://www.wellho.net/mouth/956_Python-security-trouble-with-input.html and a rather contentious discussion on this very list - http://mail.python.org/pipermail/tutor/2007-August/056328.html - and it doesn't validate the input. A better way to write this would be x = float(raw_input("Enter a number between 1 and 0: ")) y = float(raw_input("Enter a second number between 1 and 0: ")) which is safer and guarantees that x and y are floating point numbers. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Anyone fancy giving me some tips and an expert opinion??
I'll throw in a couple of ideas, but I won't pretend to be an expert. ;-) >I have written what i see as a pretty decent script to resolve this > question: > > Write an improved version of the Chaos program from Chapter 1 that allows > a > user to input two initial > values and the number of iterations and then prints a nicely formatted > table > showing how the values > change over time. For example, if the starting values were .25 and .26 > with > 10 iterations, the table > might look like this: > index 0.25 0.26 > > 1 0.731250 0.750360 > 2 0.766441 0.730547 > 3 0.698135 0.767707 > 4 0.821896 0.695499 > 5 0.570894 0.825942 > 6 0.955399 0.560671 > 7 0.166187 0.960644 > 8 0.540418 0.147447 > 9 0.968629 0.490255 > 10 0.118509 0.974630 > > Although it works I am sure I could have gone about this a better way, it > probably doesn't fit all the rules of best practice either. Was wondering > if > anyone would mind having a look and offering a few tips?? > > # chaos.py > # A program to mimic the chaos theory > > def main(): > >print "Example of Chaos" > ># User inputs numbers to compare, z is for the index counter >x = input("Enter a number between 1 and 0: ") >y = input("Enter a second number between 1 and 0: ") Generally, additional checks are made to make sure that the values actually are within the proper range, but I wouldn't think that would be necessary in such a specific script. >z = 0 > ># Prints the table borders and titles >print '%10s %20s %20s' % ("Index", x, y) >print "--" Can be print "-" * 58 >tempx = x >tempy = y You never use x and y again. Why are you changing variables to tempx and tempy? > ># Loops calculates 'chaotic behaviour for input numbers >for i in range(10): >tempx = 3.9 * tempx * (1 - tempx) >tempy = 3.9 * tempy * (1 - tempy) >z = z + 1 ># Print chaotice results into table >print '%10s %20s %20s' % (z, tempx, tempy) > >raw_input("Press any key to exit") > > main() This is really so short of a script, I wouldn't change the design, but some general tips to think about follow... My biggest worry is whether or not you will change how you print your results in a larger piece of code. For example. If you notice, when you print out your columns, you have "%10s %20s %20s" in two different places. What if you wanted to change the code so that the first column was padded to fifteen characters instead of just 10? You would have to change it in all of those places and if you missed one~ bam! Bug. The easy way to fix that is to assign the pattern to a variable and then you only have to change it once. pat = "%10s %20s %20s" print pat % (z,x,y) Will still work. ;-) The only other issue I have with this is the issue of the Z counter. In your loop you allow i to be a counter from 0 to 9. Why don't you take advantage of that? Get rid of the z variable entirely and just use 'i'. A nice script though. Keep going. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pixelize ubuntu python script acting odd.
Some suggestions throughout > def runThrough(): >walk = os.walk("/media/sda1/Documents/Pictures/2007") #location of the > pics I want to use >count = 0 >for root, dirs, files in walk: >try: >for x in files: >if x.lower().find(".jpg")> -1: #If it's a .jpg... This could be if x.lower().endswith(".jpg"): >count = count + 1 >operation = 'make_db ' + root + '/' + x This could be also operation = "make_db %s/%s" % (root,x) >os.system(operation) # Call the command line with the > operation above >print root + '/' + x #This is optional, I did this for > debugging print "%s/%s" % (root,x) >print str(count) + " files done" print "%s files done" % count >except OSError: >print root + "/" + x + " was not included in the list" >#This was run to get rid of all the obnoxious spaces in the file > names >#try: >#for x in files: >#loc = root + '/' + x >#pic = loc.replace(' ', "_") >#os.rename(loc, pic) >#count = count + 1 >#print str(count) + "files done" >#except OSError: >#print root + '/' + x + " was not included" I don't know much about ubuntu, so I can't answer the question. Also you might consider os.path.join And since you are doing this root+'/'+x so many times, perhaps you should just assign it to a variable once and use it instead? Say~ fullpath = root+'/'+x ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
On Feb 7, 2008 6:47 PM, Alan Gauld <[EMAIL PROTECTED]> wrote: > > "Alan Gauld" <[EMAIL PROTECTED]> wrote > > >> What is the equivalent of JUnit in Python? > > > > I think the nearest equivalent is > > > > Oops, I was going top say PyUnit then remembered the name > had changed but forgot to check out the latest incarnation. > Fortyunately others have done the work for me. > > Personally I like the Nose framework that comes with > TurboGears but even hand written unit tests are no big > deal in Python - just use asserts and other invariant > checks and tests etc liberally > > > Alan G. PyUnit: It really doesn't seem to be an "absolute beginner" technique. The noun/verb/adjective technique seems to be geared more towards beginners. I like the idea of that technique. Perhaps the "unit test" approach is more for "Intermediate" learners, or learners who already have a background in OOP of some form or another (like Java). I'm just starting out, so I'm looking at everything that is thrown at me, but quite frankly, it is really easy for me to see something that is over my head at this point. If it's over my head, I'll just stall, like I have in the past, and then I'll have to start this thread over again later. 8^D I guess you can tell it's been a long day for me. I've done some reading, some coding, some experimenting... all in a day's play for a Hobbyist Programmer. 8^D I'll take another look at PyUnit tomorrow morning when I'm fresh. One thing I'm encouraged by: in Alan's tutorial, he says that I don't have to "see the light" to use POOP. But if I can learn some basic "design POOP" techniques from all this, then I'll be happy. After all, I'm a beginner... you can't get any more basic than that! Happy Happy Joy Joy. -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
"Alan Gauld" <[EMAIL PROTECTED]> wrote >> What is the equivalent of JUnit in Python? > > I think the nearest equivalent is > Oops, I was going top say PyUnit then remembered the name had changed but forgot to check out the latest incarnation. Fortyunately others have done the work for me. Personally I like the Nose framework that comes with TurboGears but even hand written unit tests are no big deal in Python - just use asserts and other invariant checks and tests etc liberally Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
On Feb 7, 2008 4:58 PM, Eric Brunson <[EMAIL PROTECTED]> wrote: > bhaaluu wrote: > > What is the equivalent of JUnit in Python? The article says that JUnit is > > used for unit tests, or you can write your own. Since I don't have a clue, > > writing my own is probably out the question. Also I'm not familiar with > > Java, and am just learning Python OOP, so I'm not getting much out > > of that one. Sorry. Absolute Beginner here. > > > > http://www.google.com/search?q=python+unit+test > > Cleverly called "unittest", though sometimes referred to by its original > project name "PyUnit". > > :-) > Cool! http://docs.python.org/lib/module-unittest.html The Python unit testing framework, sometimes referred to as ``PyUnit,'' is a Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in turn, a Java version of Kent's Smalltalk testing framework. Each is the de facto standard unit testing framework for its respective language. Who would have thunk it? I'll Google and see if I can find a nice PyUnit tutorial. So, is my first try dong a "unit test" a total bit-bucket case? No way to make a "test case" out of it? That would be a good example (for me). 8^D -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
"bhaaluu" <[EMAIL PROTECTED]> wrote > What is the equivalent of JUnit in Python? I think the nearest equivalent is > writing my own is probably out the question. Also I'm not familiar > with > Java, and am just learning Python OOP, so I'm not getting much out > of that one. Sorry. Absolute Beginner here. Note that Unit testing is orthogonal to OOP. You can use TDD and unit tests(and should!) when doing procedural programming just as well. > Well, most of these were local variables in main() in the procedural > version of this program. So DataClass() is what I should name such > a class. I was wondering about that. While you can use classes that way it leads to a style of programming called object based rather than object oriented. It uses objects but the underlying design is still procedural. Thats why its better to focus on the behaviour of the objects and add the data attributes needed to support that behaviour. Remember we communicate with objects by sending them messages asking them to *do* stuff not to get data out of them, or at least we should do. "Objects do it to themselves": The Law of demeter. Ask What does this object do? What data does it need to achieve that? > Castle setup in it's own class because it is an object (using the > "model as a real-world object" method). Yes, each object should initialise its own data. (Albeit maybe based on values passed into the constructor.) HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
bhaaluu wrote: > What is the equivalent of JUnit in Python? The unittest module is based on JUnit. http://docs.python.org/lib/module-unittest.html Here is a simple introduction to the capabilities of unittest. It doesn't do much to motivate the examples though: http://www.oreillynet.com/onlamp/blog/2007/09/pymotw_unittest.html A longer intro: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html An alternative to unittest is doctest. They both get the job done, which one to use is mostly a matter of preference and the complexity of the tests. http://docs.python.org/lib/module-doctest.html Wikipedia has a short introduction to doctest and a link to Tim Peter's c.l.py posting introducing the module: http://en.wikipedia.org/wiki/Doctest http://groups.google.com/group/comp.lang.python/msg/1c57cfb7b3772763 Another intro: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-2-doctest.html There are many other testing tools that are not in the standard library. Nose and py.test are popular alternatives to unittest and doctest. http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-3-pytest-tool.html Here is a good list of testing articles: http://www.pycheesecake.org/wiki/AgileTestingArticlesAndTutorials Here is a pretty comprehensive list of tools: http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
bhaaluu wrote: > What is the equivalent of JUnit in Python? The article says that JUnit is > used for unit tests, or you can write your own. Since I don't have a clue, > writing my own is probably out the question. Also I'm not familiar with > Java, and am just learning Python OOP, so I'm not getting much out > of that one. Sorry. Absolute Beginner here. > http://www.google.com/search?q=python+unit+test Cleverly called "unittest", though sometimes referred to by its original project name "PyUnit". :-) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
On Feb 7, 2008 4:07 PM, Kent Johnson <[EMAIL PROTECTED]> wrote: > bhaaluu wrote: > > > The TDD method is the method used in my tutorial: > > Python Programming for the Absolute Beginner 2E. Michael Dawson. 2006. > > Dawson uses a very simple Tamagotchi example called Critter Caretaker > > to introduce the mechanics of POOP. However, perhaps he is using > > the TDD method of "design"? > > I don't think Dawson uses TDD. AFAIK he doesn't talk about unit-testing > at all, which is the fundamental practice of TDD. For an example of unit > tests in Python, see > http://docs.python.org/lib/minimal-example.html > > > here is > > a first little testing snippet from the testing directory, using the TDD > > method. I'm confident that if I am using the terminology incorrectly, > > someone will point out the error of my ways. > > I think you are using the terminology incorrectly. I would call this an > example of experimental programming, maybe. A classic example of TDD in > Java is here: > http://junit.sourceforge.net/doc/testinfected/testing.htm What is the equivalent of JUnit in Python? The article says that JUnit is used for unit tests, or you can write your own. Since I don't have a clue, writing my own is probably out the question. Also I'm not familiar with Java, and am just learning Python OOP, so I'm not getting much out of that one. Sorry. Absolute Beginner here. > > > class TestClass1(object): > > """ please give me a better name""" > > def __init__(self): > > """please document me""" > > self.name = "" > > self.answer = "" > > self.strength = 20 > > self.wealth = 45 > > self.light = 0 > > self.tally = 0 > > This is a good example of a data class - a class that is just a > container for data. That is a code smell. It seems to contain unrelated > values - name and strength are attributes of the player, light is an > attribute of the environment. So it should probably be more than one > class, or, since the entire program is in one loop, these could just be > local variables of main(). Well, most of these were local variables in main() in the procedural version of this program. So DataClass() is what I should name such a class. I was wondering about that. These variables were all initialized in the procedural program before the loop started. Also, the Castle was setup as part of the initialization, but I'm not dealing with that here. I'm just trying to learn how to design here. I figured I'd put the Castle setup in it's own class because it is an object (using the "model as a real-world object" method). I don't think I can worry about whether the CodeSmells at this point. I'm thinking I need to design something that works, then be able to "refactor" it to eliminate as many CodeSmells as I can. But! Noted: a DataClass is a CodeSmell. > > > def main(): > > tc1 = TestClass1() # instance > > tc1.__init__() # invoke method > > The __init__() method is called implicitly by calling TestClass1(). > Generally the only time you explicitly call __init__() is when calling > the method of a base class. I can fix that right now! Back to the laboratory! 8^D > > Kent > Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
bhaaluu wrote: > The TDD method is the method used in my tutorial: > Python Programming for the Absolute Beginner 2E. Michael Dawson. 2006. > Dawson uses a very simple Tamagotchi example called Critter Caretaker > to introduce the mechanics of POOP. However, perhaps he is using > the TDD method of "design"? I don't think Dawson uses TDD. AFAIK he doesn't talk about unit-testing at all, which is the fundamental practice of TDD. For an example of unit tests in Python, see http://docs.python.org/lib/minimal-example.html > here is > a first little testing snippet from the testing directory, using the TDD > method. I'm confident that if I am using the terminology incorrectly, > someone will point out the error of my ways. I think you are using the terminology incorrectly. I would call this an example of experimental programming, maybe. A classic example of TDD in Java is here: http://junit.sourceforge.net/doc/testinfected/testing.htm > class TestClass1(object): > """ please give me a better name""" > def __init__(self): > """please document me""" > self.name = "" > self.answer = "" > self.strength = 20 > self.wealth = 45 > self.light = 0 > self.tally = 0 This is a good example of a data class - a class that is just a container for data. That is a code smell. It seems to contain unrelated values - name and strength are attributes of the player, light is an attribute of the environment. So it should probably be more than one class, or, since the entire program is in one loop, these could just be local variables of main(). > def main(): > tc1 = TestClass1() # instance > tc1.__init__() # invoke method The __init__() method is called implicitly by calling TestClass1(). Generally the only time you explicitly call __init__() is when calling the method of a base class. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
Also beware the difference between reassigning and extending: class F: a = 3 b = [] def __init__(self, a, b): self.a = a self.b.append(b) def show(self): print self.a, self.b f1=F(1,2) f2=F(3,4) f1.show() # 1 [2, 4] f2.show() # 3 [2, 4] -- Bob Gailer 919-636-4239 Chapel Hill, NC ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Thought of some other things.
> Date: Thu, 7 Feb 2008 00:05:54 -0500> From: [EMAIL PROTECTED]> To: [EMAIL > PROTECTED]; Tutor@python.org> Subject: Re: [Tutor] Thought of some other > things.> > On Feb 6, 2008 11:38 PM, Timothy Sikes <[EMAIL PROTECTED]> wrote:> > >> > First off, I was running my script from my flash drive-That could have > caused something. Next, I have possible found something IN the location > where I ran the script, I found a pic_db.bat with stuff in it... It still > doesn't explain why the program crashed, but it does explain why I didn't > think it was doing anything.> > Your question is unclear, Timothy.> Running > from the flash drive is not going to cause your program to> crash. The > interpreter is in the PATH of your computer and you can run> your program > from flash drive, cd or from the floppy drive.> > pic_db.bat could be > anything. Google for it and verify if it is not a virus.> > Paste the error > message you received for more specific response.> > Thanks,> > Well, the > problem was I wasn't getting an error message. My computer would just stop > and log me off. Sorry I didn't specify before, but the pic_db.bat is the > result of the 'make_db' command. So it basically started to work, then > crashed my computer. I meant to ask whether or not anyone could see anything > that would cause my system to restart, but it's not necissary now. For some > reason, when I ran this script the second time, only this time saving the > list of files to a list, and then using the 'make_db' command on each and > every file in the list seemed to work. If anyone can tell me why my computer > restarted off the top of thier head, great, but otherwise I"m not going to > worry about it now Thanks though! > > -- > -- > O.R.Senthil Kumaran> http://phoe6.livejournal.com> > > ___> Tutor maillist - > > Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor _ Climb to the top of the charts! Play the word scramble challenge with star power. http://club.live.com/star_shuffle.aspx?icid=starshuffle_wlmailtextlink_jan___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: designing POOP
Sorry, my bad - this was my me, but I forgot to hit "Reply All". Here's a situation I often encounter, and I was wondering what the "best practice" is. I've generally initialized my classes' attributes this same way: > class TestClass1(object): > """ please give me a better name""" > def __init__(self): > """please document me""" > self.name = "" > self.answer = "" > self.strength = 20 > self.wealth = 45 > self.light = 0 > self.tally = 0 but it could also be done like so: > class TestClass1(object): > """ please give me a better name""" > name = "" > answer = "" > strength = 20 > wealth = 45 > light = 0 > tally = 0 > def __init__(self,name="Zed"): > """please document me""" > self.name = name > ...etc. I realize that the two are NOT equivalent if you're using the class as a static class, rather than instantiating it (e.g. using a static class called Global while weaning oneself from global variables...) However, I'm asking about this present case: the class under discussion will always be instantiated. It seems to me that declaring the attributes in the class body makes the class more amenable to introspection, but are there downsides I'm not seeing? What's the best practice? Standing by to get flamed... -- www.fsrtechnologies.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
> Sorry, my bad - this was my me, but I forgot to hit "Reply All". My me? I think I meant to type "my message". -- www.fsrtechnologies.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
bhaaluu wrote: > Best practice? Use class attributes when you actually want a shared attribute, for example for constants with class scope, or as defaults when instance attributes may not be assigned. Class attributes can be redefined by subclasses which makes them useful as a way to configure a class. Don't use them strictly as documentation. Write a docstring instead. My $.02 Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
I was asked: Here's a situation I often encounter, and I was wondering what the "best practice" is. I've generally initialized my classes' attributes this same way: > class TestClass1(object): > """ please give me a better name""" > def __init__(self): > """please document me""" > self.name = "" > self.answer = "" > self.strength = 20 > self.wealth = 45 > self.light = 0 > self.tally = 0 but it could also be done like so: > class TestClass1(object): > """ please give me a better name""" > name = "" > answer = "" > strength = 20 > wealth = 45 > light = 0 > tally = 0 > def __init__(self,name="Zed"): > """please document me""" > self.name = name > ...etc. I realize that the two are NOT equivalent if you're using the class as a static class, rather than instantiating it (e.g. using a static class called Global while weaning oneself from global variables...) However, I'm asking about this present case: the class under discussion will always be instantiated. It seems to me that declaring the attributes in the class body makes the class more amenable to introspection, but are there downsides I'm not seeing? What's the best practice? I've tried both ways and can't see any difference between the two as far as input/output is concerned. Best practice? -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A bit about python culture
On Feb 7, 2008 5:44 AM, Michael Bernhard Arp Sørensen <[EMAIL PROTECTED]> wrote: > Greetings Masters. > > I was wondering if there's a well know word for python programmers, that is > usable as a domain name. Unfortunately, "pug.dk", as in "python user group, > Denmark", is unavailable here in Denmark. > > I hope to acquire a national domain name and let future local user groups > choose their own third level domain name. > > Any ideas are welcome. > > -- > Kind regards > > Michael B. Arp Sørensen > Programmer / BOFH > > I am /root and if you see me laughing you better have a backup. > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Your best bet might be to look at the old comedy sketches of Monty Python's Flying Circus. I've found several of their skits on YouTube. A couple of the more well known sketches are the Cheese Shop and the Dead Parrot, but there are others that may also be a source of ideas for names of a Python Programming domain. Even though the logo for many Python Programming sites is a python snake, the Python Programming language was named after the British comedy troupe. Happy Happy Joy Joy. -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
Greetings, I've read both Kent's and Alan's approaches to designing a POOP, and am intrigued with the possibilities of the noun/verb/adjective technique, but am also sympathetic to the TDD method as well because it is how I've always programmed. I have noted Alan's comments on the limitations of TDD, as well as the limitations of the noun/verb/adjective method of design. The TDD method is the method used in my tutorial: Python Programming for the Absolute Beginner 2E. Michael Dawson. 2006. Dawson uses a very simple Tamagotchi example called Critter Caretaker to introduce the mechanics of POOP. However, perhaps he is using the TDD method of "design"? I'm still experimenting with the noun/verb/adjective design technique, but I was also itching to get started on something as well, so here is a first little testing snippet from the testing directory, using the TDD method. I'm confident that if I am using the terminology incorrectly, someone will point out the error of my ways. The Tutors are always saying they really can't help unless they see some code, so this is a simple adventure game that involves switching a light on and off. The gameplay isn't all that great, but it is a start. 8^D #!/user/bin/python """ >From the testing laboratory of: b h a a l u u at g m a i l dot c o m 2008-02-07 """ import time CS = "\n"*50 class TestClass1(object): """ please give me a better name""" def __init__(self): """please document me""" self.name = "" self.answer = "" self.strength = 20 self.wealth = 45 self.light = 0 self.tally = 0 def main(): tc1 = TestClass1() # instance tc1.__init__() # invoke method print CS N1 = tc1.name N1 = raw_input(" WHAT IS YOUR NAME, EXPLORER? ") # main game loop while True: print CS print (" %s, YOUR STRENGTH IS %d") % (N1, tc1.strength) print (" YOU HAVE $%d") % tc1.wealth if tc1.light == 0: print (" IT IS TOO DARK TO SEE ANYTHING") else: print (" THE LIGHT'S ON, BUT NO ONE'S HOME") print print A = tc1.answer A = raw_input(" WHAT DO YOU WANT TO DO? [Q|L]: ") # main game prompt if A.upper() == "Q": break if A.upper() == "L": light = raw_input(" LIGHT? [0|1]: ") # turn the light on and off if light == 0 and tc1.light == 0: print (" THE LIGHT IS OFF") time.sleep(2) if tc1.wealth <= 0: print print (" YOU HAVE NO MONEY") time.sleep(2) else: tc1.light = int(light) tc1.wealth -= 15 else: print (" INVALID CHOICE") time.sleep(2) tc1.tally += 1 tc1.strength -= 5 if tc1.strength <= 0: print (" YOU DIED") time.sleep(2) break print print (" Final Score:") print ("Tally: %d") % tc1.tally print (" Wealth: $%d") % tc1.wealth print (" Strength: %d") % tc1.strength if __name__ == "__main__": main() On Feb 7, 2008 4:15 AM, Alan Gauld <[EMAIL PROTECTED]> wrote: > "Kent Johnson" <[EMAIL PROTECTED]> wrote > > > Let me say that I don't mean any disrespect for Alan or his > > approach, I > > just have a different point of view. > > Heh, heh! I was waiting for someone to post a message like this. > I'll respond by saying the noun/verb thing is not actually the > method I would normally use (although when all else fails I > do drop back to it as a starter technique). However I have found > it to be a techhnique that woerks well for beginners who don't > know how to get started. Partly because it is fairly mechanistic. > > But noun/verb does have some problems and often produces > designs that have too many classes and that do not make > best use of OOP idioms like polymorphism or abstraction. > But for beginners and in small problems it is a good starter. > > > Also I will say that converting a procedural program to OO 'just > > because' is not necessarily a good idea. Not every program is > > improved > > by OOP. In your case, it probably will be though. > > This is absolutely true. Too many people approach OOP as > if it were some kind of holy grail that is inherently better > than other styles - it isn't, its just another tool in the toolkit. > > > I tend to work from small pieces to larger ones and let the design > > grow > > from the needs of the code, rather than from considerations of nouns > > and > > verbs in the spec. > > I agree at the micro level and in fact my discussion of > explorers and monsters merging into a figher superclass > hopefully illustrates how that micro level design/code cycle > can generate new features of a design including new > classes/objects. Many OO Design gurus have commented > on the way that OO design tends to cycle between top down > design - identifying core classes - and bo
Re: [Tutor] A bit about python culture
>Michael Bernhard Arp Sørensen wrote: >> Greetings Masters. >> >> I was wondering if there's a well know word for python programmers, that >> is usable as a domain name. > >Pythonista is one. pythonista.dk seems to be available. > >Kent Other available .dk domains pyproject.dk pyprojects.dk python-project.dk pythonprogram.dk These might be used for project subdomains, then the programmers might add their name in E-mail adresses. Doing this you will also marked Python projects + making people aware of Python as a programming language. Just a thought :) BR Thomas >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Anyone fancy giving me some tips and an expert opinion??
I have written what i see as a pretty decent script to resolve this question: Write an improved version of the Chaos program from Chapter 1 that allows a user to input two initial values and the number of iterations and then prints a nicely formatted table showing how the values change over time. For example, if the starting values were .25 and .26 with 10 iterations, the table might look like this: index 0.25 0.26 1 0.731250 0.750360 2 0.766441 0.730547 3 0.698135 0.767707 4 0.821896 0.695499 5 0.570894 0.825942 6 0.955399 0.560671 7 0.166187 0.960644 8 0.540418 0.147447 9 0.968629 0.490255 10 0.118509 0.974630 Although it works I am sure I could have gone about this a better way, it probably doesn't fit all the rules of best practice either. Was wondering if anyone would mind having a look and offering a few tips?? # chaos.py # A program to mimic the chaos theory def main(): print "Example of Chaos" # User inputs numbers to compare, z is for the index counter x = input("Enter a number between 1 and 0: ") y = input("Enter a second number between 1 and 0: ") z = 0 # Prints the table borders and titles print '%10s %20s %20s' % ("Index", x, y) print "--" tempx = x tempy = y # Loops calculates 'chaotic behaviour for input numbers for i in range(10): tempx = 3.9 * tempx * (1 - tempx) tempy = 3.9 * tempy * (1 - tempy) z = z + 1 # Print chaotice results into table print '%10s %20s %20s' % (z, tempx, tempy) raw_input("Press any key to exit") main() Thanks!!! And thanks for all the help you've all supplied me with so far, you guys certainly are an extremely valuable resource!! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A bit about python culture
On 07/02/2008, Michael Bernhard Arp Sørensen <[EMAIL PROTECTED]> wrote: > Greetings Masters. > > I was wondering if there's a well know word for python programmers, that is > usable as a domain name. Unfortunately, "pug.dk", as in "python user group, > Denmark", is unavailable here in Denmark. > > I hope to acquire a national domain name and let future local user groups > choose their own third level domain name. > > Any ideas are welcome. > [EMAIL PROTECTED]:~$ whois python.dk # Any use of this material to target advertising or similar activities # are explicitly forbidden and will be prosecuted. DK Hostmaster A/S # requests to be notified of any such activities or suspicions thereof. Domain: python.dk DNS: python.dk Registered: 1999-09-14 Expires: 2008-09-30 Registration period: 1 year VID: no Status: Active Nameservers Hostname: ns1.rackserverz.biz Hostname: ns2.rackserverz.biz [EMAIL PROTECTED]:~$ whois pyden.dk # Any use of this material to target advertising or similar activities # are explicitly forbidden and will be prosecuted. DK Hostmaster A/S # requests to be notified of any such activities or suspicions thereof. No entries found for the selected source. [EMAIL PROTECTED]:~$ pyden.dk doesn't sound too bad. Dotan Cohen http://what-is-what.com http://gibberish.co.il א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
Alan Gauld wrote: > "Kent Johnson" <[EMAIL PROTECTED]> wrote >> The writings of Robert C Martin have taught me a lot about good >> design >> and agile development. They don't all apply to Python > > Martin is very good on Agile, I'm less impressed with his OO writing, > largely because he does tend to see the world through the eyes > of C++ and Java, both of which have a very singular view of OO > which does not always work in other more dynamic OOP > languages (Lisp, Smalltalk, Python, JavaScript etc) I found his writing on principles of OO design very helpful when I was a C++ programmer. I admit I have not revisited them from the point-of-view of a Python programmer. I'm sure some of the techniques are not needed - the pervasive use of interfaces, in particular - but the underlying principles should still apply. Taking a closer look, I think these still have something to offer: The Liskov Substitution Principle http://objectmentor.com/resources/articles/lsp.pdf Inheritance vs. Delegation (Template Method and Strategy patterns) http://objectmentor.com/resources/articles/inheritanceVsDelegation.pdf The Craftsman series might be of interest. One thing to keep in mind is that when C++ and Java use interfaces, Python uses duck typing. C++ and Java use classes to encapsulate functions (e.g. in Strategy) but Python can use functions directly. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A bit about python culture
Michael Bernhard Arp Sørensen wrote: > Greetings Masters. > > I was wondering if there's a well know word for python programmers, that > is usable as a domain name. Pythonista is one. pythonista.dk seems to be available. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] A bit about python culture
Greetings Masters. I was wondering if there's a well know word for python programmers, that is usable as a domain name. Unfortunately, "pug.dk", as in "python user group, Denmark", is unavailable here in Denmark. I hope to acquire a national domain name and let future local user groups choose their own third level domain name. Any ideas are welcome. -- Kind regards Michael B. Arp Sørensen Programmer / BOFH I am /root and if you see me laughing you better have a backup. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] A bit about python culture
Greetings Masters. I was wondering if there's a well know word for python programmers, that is usable as a domain name. Unfortunately, "pug.dk", as in "python user group, Denmark", is unavailable here in Denmark. I hope to acquire a national domain name and let future local user groups choose their own third level domain name. Any ideas are welcome. -- Kind regards Michael B. Arp Sørensen Programmer / BOFH I am /root and if you see me laughing you better have a backup. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
On Feb 6, 2008 8:15 PM, Kent Johnson <[EMAIL PROTECTED]> wrote: > > Design a little, code a little, repeat... > http://personalpages.tds.net/~kent37/stories/3.html > > > You can discover many useful design techniques by applying DRY. More here: > http://personalpages.tds.net/~kent37/stories/00012.html > > > It has a chapter that explains the code smells and points out > ways to fix them. An abbreviated version is available here: > http://wiki.java.net/bin/view/People/SmellsToRefactorings > > The writings of Robert C Martin have taught me a lot about good design > and agile development. A lot of his work is available on-line: > http://objectmentor.com/resources/publishedArticles.html > > http://objectmentor.com/resources/articles/Principles_and_Patterns.pdf > might be a good starting point. > http://objectmentor.com/resources/articles/xpepisode.htm attempts to > give the flavor of agile, test-driven development. > > I don't use the command-line interpreter much, I do a lot more work in > unit tests. I have written a little more about this here: > http://personalpages.tds.net/~kent37/stories/7.html > > HTH, > Kent Thank you Kent! I am open to all suggestions as to where to get started learning how to design with the Python Object-Oriented Paradigm. I'm doing a lot of reading, some coding (in my 'testing' directory), and a lot of thinking about what I'm trying to do. This is a learning situation. Since I'm a Hobbyist programmer, I don't have a 'class' deadline to meet (and believe me, I'm happy about that!). I do feel that learning how to do this will enhance the enjoyment of my Hobby for years to come. I do know that it will open a lot of doors for me that are currently closed, especially when it comes to creating games with Python/PyGame, and so forth. Plus, it is quite possible that this discussion will benefit others who are also just beginning. Happy Happy Joy Joy. -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] designing POOP
"Kent Johnson" <[EMAIL PROTECTED]> wrote > Let me say that I don't mean any disrespect for Alan or his > approach, I > just have a different point of view. Heh, heh! I was waiting for someone to post a message like this. I'll respond by saying the noun/verb thing is not actually the method I would normally use (although when all else fails I do drop back to it as a starter technique). However I have found it to be a techhnique that woerks well for beginners who don't know how to get started. Partly because it is fairly mechanistic. But noun/verb does have some problems and often produces designs that have too many classes and that do not make best use of OOP idioms like polymorphism or abstraction. But for beginners and in small problems it is a good starter. > Also I will say that converting a procedural program to OO 'just > because' is not necessarily a good idea. Not every program is > improved > by OOP. In your case, it probably will be though. This is absolutely true. Too many people approach OOP as if it were some kind of holy grail that is inherently better than other styles - it isn't, its just another tool in the toolkit. > I tend to work from small pieces to larger ones and let the design > grow > from the needs of the code, rather than from considerations of nouns > and > verbs in the spec. I agree at the micro level and in fact my discussion of explorers and monsters merging into a figher superclass hopefully illustrates how that micro level design/code cycle can generate new features of a design including new classes/objects. Many OO Design gurus have commented on the way that OO design tends to cycle between top down design - identifying core classes - and bottom up design - writing the lowest building blocks and using that to discover more about the higher level needs. OO design is a very organic process compared to procedural design which tends to bemuch more top down and heirarchical in nature. In my experience at least. > accommodate it. Design a little, code a little, repeat... > http://personalpages.tds.net/~kent37/stories/3.html Exactly so. > The writings of Robert C Martin have taught me a lot about good > design > and agile development. They don't all apply to Python Martin is very good on Agile, I'm less impressed with his OO writing, largely because he does tend to see the world through the eyes of C++ and Java, both of which have a very singular view of OO which does not always work in other more dynamic OOP languages (Lisp, Smalltalk, Python, JavaScript etc) > I don't use the command-line interpreter much, I do a lot more work > in > unit tests. In test-driven development (TDD), if you decide you want > a > Room class, the first thing you do is create a unit test for the > class. For production programming I wholly endorse that approach, for exploring and inventing code structures (which is mainly what I use Python for, the results get converted to Java where we use TDD) I find the interpreter is very useful. To use TDD effectively you first need to know what you are trying to do. An example of bad use of TDD can be found in one of Robert Martins books where he tries to give an example of pair programming of a bowling game scorer. Unfortunately because of the haphazard design approach they wind up with code that is both bloated (it repeats an algorithm twice) and faulty (one of the algorithm implementations is broken). Unfortunately they don't detect the fault because the test data they used missed out all of the cases where the defect is exhibited... Note it wasn't the test that was broken it was the limited data set used. And that is one of the big limitations of TDD, it is only as effective as the test data. It is important to realize that there is no single way to design OOP programs. The noun/verb thing is a good way to get started and often effective when nothing else seems to be working. But there are plenty of other approaches out there and books by authors like Booch, Rumbaugh, Jacobsen, Schaer/Mellor, Coad/Yourdon, Wirfs-Brock and yes, Robert Martin are all worh reading to see the different approaches available. The Coad/Nicola OOP book is especially interesting because it contrasts the same problems in C++ and Smalltalk (which is conceptually close to python) and shows how the choice of language can have a big impact on detailed OOP design decisions. Once you get experienced in OPP you will not use the noun/verb te4chnique very often because your brain will start to think in terms of objects without need of intermediate tools. In fact when I went back to COBOL for the Y2K bug I found it hard initially to think procedurally because I'd been using OOP for so long by then. Nowadays I don;t write so much code I find I switch between both modes of design without really thinking too much about it. On small scale stuff I tend to go procedural but on big problems I tend to go OOP. Alan G. ___ Tutor m