Re: [Tutor] Beginner Question
On Wed, 10/23/13, Steven D'Aprano wrote: Subject: Re: [Tutor] Beginner Question To: tutor@python.org Date: Wednesday, October 23, 2013, 5:27 AM On Tue, Oct 22, 2013 at 04:25:59PM +0200, Sven Hennig wrote: > Hello, I would like to learn a programming language and have decided to use > Python. I have some programming experience and doing well in Python. What > really causes me problems is OOP. > I'm just dont get it... I'm missing a really Practical example. In every > book I've read are the examples of such Class Dog and the function is bark. Has > anyone an OOP example for me as it is really used in real code, so I can > better understand the concept? I do not know why this is so hard for me. I can sympathise. You wouldn't believe how long it took me to really grok object-oriented programming. I just didn't get it, until I started thinking of OOP as being just syntax for keeping functions (called "methods") close to the data they belong with. There is more to OOP than that, but that was my first step: OOP helps you keep your functions close to the data they work with. That's all you need to know to start using object oriented programming in Python! Many operations are implemented as methods, for instance strings have upper and lower methods, lists have append and remove methods, and many more. You'll soon learn the operations like len() that aren't methods, but old-school functions. ==> This reminded me of a text by Guido van Rossum (I can't find the original page): http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm So the built-in 'len()' is *really* a function, but calls to len() implemented by __len__ are method calls *disguised* as function calls? I sometimes find it easier to write calls to special methods the "normal" way, e.g. instead of "x + y" just write it like "x.__add__(y)" This makes special methods more like other methods and therefore easier to understand, to me at least. Albert-Jan PS: sorry about the lack of quoting. Yahoo mail was "upgraded" and now all sorts of stuff stops working, times out, etc. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Beginner question on classes
Hi guys, I need a bit of help. I'm writing a class, and in the main function I'm trying to say if this method gets called, do this. I'm trying things like: program = AnimalClass(x,y,z)for i in range(x): for j in range(y): for k in range(z): animal = program.animal() if animal: if isinstance(animal,moose): print("There is a moose here") It's clearly not correct because it's giving me all sorts of grief, but if anyone knows how to do this correctly I'd very much appreciate it! Corrine ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner Question
On 23 October 2013 08:58, Albert-Jan Roskam wrote: > So the built-in 'len()' is *really* a function, but calls to len() > implemented by __len__ are method calls *disguised* as function calls? I > sometimes find it easier to write calls to special methods the "normal" way, > e.g. instead of "x + y" just write it like "x.__add__(y)" This makes special > methods more like other methods and therefore easier to understand, to me at > least. Please don't do that. Firstly it looks horrible. Secondly they're not equivalent. The equivalent of x + y is operator.add(x, y) but don't use that either. It's not easier to understand and it's less efficient. When you wrate a+b the interpreter actually calls a bunch of different methods: a.__add__(b), b.__radd__(a), a.__coerce__(b) etc. I don't know the full sequence and it's not consistent across Python implementations. Eryksun recently posted a good example showing how a == b is handled: https://mail.python.org/pipermail/tutor/2013-July/097110.html Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner question on classes
On 23/10/13 08:25, Corinne Landers wrote: Hi guys, I need a bit of help. I'm writing a class, and in the main function I'm trying to say if this method gets called, do this. What you are actually doing is "if the method returns a truth-like value do this." Not quite the same thing, but much easier! I'm trying things like: program = AnimalClass(x,y,z) for i in range(x): for j in range(y): for k in range(z): animal = program.animal() if animal: if isinstance(animal,moose): print("There is a moose here") The block below for k... needs more indentation and The final print needs yet another level of indentation... It's clearly not correct because it's giving me all sorts of grief, Could you be more specific? What kind of grief? Error messages? Then send the full message here. Your computer crashes? It doesn't print a message you expected? While you are at it which Python version and OS are you using? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner question on classes
On 23 October 2013 08:25, Corinne Landers wrote: > Hi guys, Hi Corrine, > I need a bit of help. > I'm writing a class, and in the main function I'm trying to say if this > method gets called, do this. > I'm trying things like: > > program = AnimalClass(x,y,z) > for i in range(x): >for j in range(y): > for k in range(z): > animal = program.animal() > if animal: > if isinstance(animal,moose): > print("There is a moose here") > > It's clearly not correct because it's giving me all sorts of grief, but if > anyone knows how to do this correctly I'd very much appreciate it! I'm sure someone will help you but you haven't really given enough information yet. Is the code you posted the whole of your program? If so please say so explicitly because it looks like only part of a program to me and you should show the whole code for anyone to understand what you're doing. Also you say that it is giving you grief but we need more than that. Is it showing an error message? If so please copy/paste the whole error message and traceback. Here's an example showing what happens when I run your program as shown above (saved into a file called tmp.py): $ python tmp.py File "tmp.py", line 5 animal = program.animal() ^ IndentationError: expected an indented block What that error means is that you need to indent everything inside the 3rd for loop on line 5. Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner question on classes
On 23/10/2013 03:25, Corinne Landers wrote: > --> > Hi guys, I > need a bit of help. I'm writing a class, and in the main > function I'm trying to say if this method gets called, do > this. I'm trying things > like:program = AnimalClass(x,y,z)for i > in range(x): for j in range(y): > for k in range(z): animal = > program.animal() if > animal: if > isinstance(animal,moose): > print("There is a moose here")It's clearly not > correct because it's giving me all sorts of grief, but if anyone knows how to > do this correctly I'd very much appreciate > it!Corrine > > > Hi, and welcome to Python, and to the Python tutor list. Please start by telling us what Python version you're using, and what OS. Please post here using a text message, not html, as many email programs (apparently including yours) cannot correctly convert the html to text. Your entire program fragment appears on one line in my newsreader. And people like me can see the html, but not display it. This is a text newsgroup. Studying other people's responses that do have html abilities, I can see that you did post an indented code fragment, so I'll copy that here and comment on it. > program = AnimalClass(x,y,z) > for i in range(x): > for j in range(y): >for k in range(z): >animal = program.animal() >if animal: >if isinstance(animal,moose): >print("There is a moose here") Your problem statement was: "if this method gets called, do this" No idea which of these is "this method," nor what you intend by "do this." And you needn't test whether it's being called, since presumably you're calling it. Usually, you test the return value of a method, but that's not what you're saying. Just looking at the code in isolation, I can see that you'll get an indentation error on the line assigning to animal. You have to indent the body of any for statement. Next, it appears you don't use i, j and k. So are you intending to just do the same thing x*y*z times? If so, then you just should use one loop, and multiple them together. Does program.animal() return the same value each time, or is it somehow supposed to guess the values of i, j, and k ? Is moose a class name, defined elsewhere that you didn't include? Then it ought to be capitalized, to make that obvious. It's just a convention, but following conventions will make your code easier to read. I know that many classes in the standard lib are not capitalized, but that's mostly because the names were established many many years ago, some perhaps before there was the ability to write user classes. Pep-8 is the place where such conventions are described. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to Terminate a Popen call?
Hello eryksun, Thanks, very much, for the very quick and helpful reply. It fixed my problem. -Sm On Tue, Oct 22, 2013 at 10:33 PM, eryksun wrote: > On Tue, Oct 22, 2013 at 9:04 PM, SM wrote: > > def run(self): > > (process, err) = Popen(self.fwcmd, stdout=PIPE, > > stderr=PIPE).communicate() > > if len(err) > 0: > > # print("Error") > > # Error handling code > > else: > > # print("Success") > > Store the Popen() instance before calling its communicate() method: > > p = self.process = Popen(self.fwcmd, stdout=PIPE, stderr=PIPE) > out, err = p.communicate() > if p.returncode: > raise CalledProcessError(p.returncode, self.fwcmd, (out, err)) > > communicate() sets returncode; an error is indicated by a non-zero > value. Some programs write non-error information to stderr, so use the > return code to detect an error. > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] The meaning of self
I have come across the term "self" in a number of Python scripts and as a beginner to the language I am wondering if it has any specific meaning. It is usually used in the same manner as in this example by Steven D'Aprano. class DefaultModelCar: model = "Unknown" BRAKE_COMMAND = "B" FORWARD_COMMAND = "F" REVERSE_COMMAND = "R" ACCELERATE_COMMAND = "A" TURN_LEFT_COMMAND = "TL" TURN_RIGHT_COMMAND = "TR" def send_command(self, command): # Send a command to the model car. # Put the code here to actually communicate with the car. ... def forward(self): # Drive forward. if self.direction == "Reverse": # Brake first, then move forward. self.stop() self.send_command(self. FORWARD_COMMAND) self.send_command(self.ACCELERATE_COMMAND) self.direction = "Forward" def reverse(self): if self.direction == "Forward": self.stop() self.send_command(self.REVERSE_COMMAND) self.send_command(self.ACCELERATE_COMMAND) self.direction = "Reverse" def stop(self): self.send_command(self.BRAKE_COMMAND) self.direction = "Stopped" -- *Glenn Lester* Software Tester *Avant Systems Group*** *voice: *204.789.9596 x19* **|** fax: *204.789.9598* **|** email: * gles...@avant.ca*|** web: *www.avant.ca** *Quality People Delivering Quality Solutions* CONFIDENTIALITY NOTICE: This correspondence and any attachment(s) may contain confidential information that is legally privileged. If you are not the intended recipient, or the person responsible for delivering it, you are hereby notified that any disclosure, copying, distribution or use of any of the aforementioned information is STRICTLY PROHIBITED. If you have received this transmission in error, please permanently delete the original transmission and its attachments without reading or saving in any manner. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] export postgresql to unified, templated xml
Hello all.i have a quite big task, but i have a feeling it could be easily solved using python. The thing is, i need to export the whole company DB(Postgresql) to an XML template provided by another company. the template looks like this(just a fragment) : ?xml version="1.0" encoding="utf-8"?> ... i've never done anything like that.i'm familiar with psycopg2 module, also, i'm familiar with xml parsing(ElementTree, lxml). is there some way to use the provided xml as a template, then parse all the data according to the template, what is the moyt pythonic way to do this? Thx. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The meaning of self
On 23/10/13 17:01, Glenn Lester wrote: I have come across the term "self" in a number of Python scripts and as a beginner to the language I am wondering if it has any specific meaning. Technically no, the name is arbitrary but self is used by (very strong) tradition. As to what it is used for the explanation depends on your background. If you already know languages like C++, Java or JavaScript then the simple explanation is that self is the equivalent of 'this' in those languages except Python requires yopu to explicitly specify it as the first parameter in any method. The other languages do this implicitly. If you don;t know those other languages then can I suggest you try reading my explanation in my tutorial here... http://www.alan-g.me.uk/l2p/tutclass.htm About 15-20% of the way down there is a heading 'What is self?' If that still makes no sense then come back and ask again, ideally with some more specific aspects to the bits that puzzle you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Want to keep to two decimal places for currency
I've looked online but I'm confused - I need to keep it so that the following program limits the output to two decimal places since it deals in currency. How do I incorporate that into my current code below? The textbook I'm using doesn't describe how to do that. Thanks in advance. #Challenge Chapter 2 #Question number three print("This program helps you to determine a tip amount of either") print("15 or 20 percent.") bill=float(input("\nHow much was your restaurant bill total (in dollars)? ")) fifteen=float(bill*0.15) twenty=float(bill*0.2) print("\n15% tip = $", fifteen) print("\n20% tip = $", twenty) input("\n\nPress the enter key to exit.") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Want to keep to two decimal places for currency
On 23/10/13 22:39, Shelby Martin wrote: I've looked online but I'm confused - I need to keep it so that the following program limits the output to two decimal places since it deals in currency. Its generally a bad idea to use floats when dealing with currency since they can introduce small errors which can accumulate over time. It's better to either use the Decimal module or to convert money to cents/.pennies and then convertback to dollars for display purposes. However, for the purposes of your homework we will ignore that. How do I incorporate that into my current code below? The textbook I'm using doesn't describe how to do that. Thanks in advance. You need tobdistinguish between storage and display. You want to maintain the data stored in its full accuracy but display it with only 2 decimal digits. One waty to do that is with the string format method (I'm assuming Python v3). Check the Python docs for string formatting and you will find several options you can use to control the display of floating point numbers. The basic form is print( "Here is a float: {}".format(123.456789) ) We can limit the field length to 7 digit swith print( "Here is a float: {:15f}".format(123.456789) ) And adjust the number of digits after the point like so: print( "Here is a float: {:7.3f}".format(123.456789) ) You can also specify justification, zero padding and other aspects. Read the docs... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Want to keep to two decimal places for currency
On Wed, Oct 23, 2013 at 4:13 PM, Alan Gauld wrote: > On 23/10/13 22:39, Shelby Martin wrote: > >> I've looked online but I'm confused - I need to keep it so that the >> following program limits the output to two decimal places since it deals >> in currency. >> > > Its generally a bad idea to use floats when dealing with currency since > they can introduce small errors which can accumulate over time. It's better > to either use the Decimal module or to convert money to cents/.pennies and > then convertback to dollars for display purposes. > Hi Shelby, If you want to read some gory details, you can find the reasons for why it's unsafe to represent currency with "floating point" numbers. There's a classic paper called "What Every Computer Scientist Should Know About Floating-Point Arithmetic": http://www.validlab.com/goldberg/paper.pdf and you probably don't want to read the whole thing. :P A rough gist of the problem: traditional, engineering-focused computer math has a particular trade-off that most programmers do not realize at first: it trades accuracy for speed. The native hardware of your computer does calculations in base-2 rather than base-10 arithmetic. Unfortunately, that means that fractional quantities take a representational hit: your computer cannot accurately represent certain decimals in base-2. It turns out that this floating point arithmetic limitation is not so bad for a lot of important applications. But it doesn't bode well at all for applications that deal with money. There are libraries in Python that avoid using the built-in floating point hardware, such as the Decimal library that Alan noted. Computations with it are slower, but that's an acceptable price for getting the dollars and cents right. If we would do this sort of thing in the real world, we'd use something like the Decimal library. You'll see equivalent kinds of libraries in other programming languages, like the BigDecimal class in Java. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor