Re: [Tutor] Understanding Classes
I would first like to state two things, those being that I am a horrible writer as well as explaining things, but Ill try my absolute best. Everything python is an object. Strings, integers, lists, so on and so forth. In regards to classes and their relativity towards objects, I am at complete standstill. However, I understand that classes are parallel to that of a blueprint, but that is unfortunately where the buck stops. On Sun, Jan 19, 2014 at 6:50 PM, Alan Gauld alan.ga...@btinternet.comwrote: On 19/01/14 21:59, Christian Alexander wrote: Looked all over the net for class tutorials Unable to understand the self argument Attempting to visual classes If you read my OOP tutorial there is a section there specifically about self. And the v3 tutor includes an introduction to the formal visualisation technique for OOP called UML. The diagrams illustrating the designs may help. http://www.alan-g.me.uk/l2p/tutclass.htm I have searched high and low, for easy to follow tutorials regarding classes. Although I grok the general concept of classes, Do you also grok the concept of objects? Classes on their own are fairly useless (unless you are using Java) it is only when you create a universe of objects from those classes that they become useful. If you can repeat to us your understanding of classes and their relationship with objects that will help us understand your level and shape our responses accordingly. to visually understand what exactly self does, or why it is even necessary. It seems very magic to me. When you define a class you define the data (attributes) that the class instances will have. Each instance will have a copy of the data defined in the __init__() method. You also define a set of operations or methods that are associated with the class. Those methods are shared by the instances. Note the difference. Instances get a copy of the attributes but they all share the methods. Thus when you invoke a method on an instance the instance relays that call to the class. For the class to know which instance is being operated on, and for the method to be able to access the correct instance's data it needs a reference to the instance. That reference is typically called 'self' or 'this'. (In some languages it's fixed but in Python self is only a convention, you can use any name you like). You can make the call to the class explicit and it will still work. See below: # define a class class MyClass: def __init__(self,x): self.x = x def myMethod(self): print(self.x) # create some instances ObjA = MyClass(2) ObjB = MyClass(4) ObjC = MyClass(6) # send some messages/call methods objA.myMethod() # call from the instance MyClass.myMethod(ObjB) # call explicitly to the class objC.myMethod() # direct again All 3 calls do the same thing except the middle one passes the object identifier directly to the class whereas the first and last both do that internally within the object structure. difficult with the __init__() method in classes, and why that is also required. It is not *required* as such. You can create a class without an init but it's unusual. When you create an instance of a class it creates a data structure in memory referenced by the name of the instance. But that structure is empty, it has no data. So to populate the data for the instances you must initialize it. That's what __init__() does. It takes the arguments you provide and applies them to the instance along with any static data definitions you may define. In the example we create an instance variable, x, within the instances and assign the value of the argument passed to init. Like any other method the actual code lives in the class so we could initialize it by calling init like so: MyClass.__init__(objC, 66) which is almost the same as doing: objC = MyClass(66) The difference is that the first case requires the object ObjC to already exist, the second example creates a new instance and then calls init on that instance. Keep in mind that I am a visual person (maybe I should have been a graphic designer), therefore most programming concepts flow irritatingly slow for me. Most programming concepts have visual representations, its just that program code being text tends to lead programmers to be verbally based. But algorithms, state machines, logic, data structures, GUIs, formal requirements and OOP all have well established visual representations, and in many cases they are formalized so that, with the right tools, you can create code purely visually. If the above doesn't clarify things, and I suspect it won't entirely, then please do express your understanding so far in your own words and we'll try to clarify things from there. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___
Re: [Tutor] string indexing
Spir and Peter, thanks for the specifics, super helpful. Alan, super thanks for the general advice, you guys are awesome!! On Mon, Jan 20, 2014 at 5:34 AM, tutor-requ...@python.org wrote: Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit https://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-requ...@python.org You can reach the person managing the list at tutor-ow...@python.org When replying, please edit your Subject line so it is more specific than Re: Contents of Tutor digest... Today's Topics: 1. Re: Understanding Classes (Alan Gauld) 2. Re: string indexing (Keith Winston) 3. Re: Question on os.popen (Alan Gauld) 4. Re: Question on os.popen (SM) 5. Re: Question on os.popen (eryksun) -- Message: 1 Date: Sun, 19 Jan 2014 23:50:59 + From: Alan Gauld alan.ga...@btinternet.com To: tutor@python.org Subject: Re: [Tutor] Understanding Classes Message-ID: lbhocn$vg3$1...@ger.gmane.org Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 19/01/14 21:59, Christian Alexander wrote: Looked all over the net for class tutorials Unable to understand the self argument Attempting to visual classes If you read my OOP tutorial there is a section there specifically about self. And the v3 tutor includes an introduction to the formal visualisation technique for OOP called UML. The diagrams illustrating the designs may help. http://www.alan-g.me.uk/l2p/tutclass.htm I have searched high and low, for easy to follow tutorials regarding classes. Although I grok the general concept of classes, Do you also grok the concept of objects? Classes on their own are fairly useless (unless you are using Java) it is only when you create a universe of objects from those classes that they become useful. If you can repeat to us your understanding of classes and their relationship with objects that will help us understand your level and shape our responses accordingly. to visually understand what exactly self does, or why it is even necessary. It seems very magic to me. When you define a class you define the data (attributes) that the class instances will have. Each instance will have a copy of the data defined in the __init__() method. You also define a set of operations or methods that are associated with the class. Those methods are shared by the instances. Note the difference. Instances get a copy of the attributes but they all share the methods. Thus when you invoke a method on an instance the instance relays that call to the class. For the class to know which instance is being operated on, and for the method to be able to access the correct instance's data it needs a reference to the instance. That reference is typically called 'self' or 'this'. (In some languages it's fixed but in Python self is only a convention, you can use any name you like). You can make the call to the class explicit and it will still work. See below: # define a class class MyClass: def __init__(self,x): self.x = x def myMethod(self): print(self.x) # create some instances ObjA = MyClass(2) ObjB = MyClass(4) ObjC = MyClass(6) # send some messages/call methods objA.myMethod() # call from the instance MyClass.myMethod(ObjB) # call explicitly to the class objC.myMethod() # direct again All 3 calls do the same thing except the middle one passes the object identifier directly to the class whereas the first and last both do that internally within the object structure. difficult with the __init__() method in classes, and why that is also required. It is not *required* as such. You can create a class without an init but it's unusual. When you create an instance of a class it creates a data structure in memory referenced by the name of the instance. But that structure is empty, it has no data. So to populate the data for the instances you must initialize it. That's what __init__() does. It takes the arguments you provide and applies them to the instance along with any static data definitions you may define. In the example we create an instance variable, x, within the instances and assign the value of the argument passed to init. Like any other method the actual code lives in the class so we could initialize it by calling init like so: MyClass.__init__(objC, 66) which is almost the same as doing: objC = MyClass(66) The difference is that the first case requires the object ObjC to already exist, the second example creates a new instance and then calls init on that instance. Keep in mind that I am a visual person (maybe I should have been a graphic designer), therefore most programming concepts flow irritatingly slow for me. Most programming concepts have
[Tutor] 4.7.5
I think I may have found a bug: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair: pair[1]) pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] Should be: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pairs: pairs[1]) pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] I have increased the size of the two s's to show the problem. Doug ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Understanding Classes
On 20/01/14 00:55, Christian Alexander wrote: I would first like to state two things, those being that I am a horrible writer as well as explaining things, but Ill try my absolute best. Everything python is an object. Strings, integers, lists, so on and so forth. In regards to classes and their relativity towards objects, I am at complete standstill. OK, we need to backup a little. Objects are the individual instances of data that we work with. This individual strings like 'foo' and 'hello' are objects. Strings in general are a class. 'foo' and 'bar' are instances of that class, or objects of that class. (instance and object are almost synonymous) Similarly for integers. 3,5,97 and 123456789 are all instances of the integer class. Of course these are built in classes of object so you don't see an explicit class defined anywhere. But classes that you define are just like those built in types. You define the structure and behaviour in the class and create instances of it to work with as objects. However, I understand that classes are parallel to that of a blueprint, Yes, they define what the objects will look like, what data and what methods they contain. But to use those objects you have to instantiate them and its there that the usage varies slightly from the built in types: For built in string type objects you do this mystring = 'a new string object' But if String were a user defined class you'd need to do this: mystring = String('a user defined string object') ie. you'd 'call' the class name with the data arguments needed. In fact in Python you can explicitly call str() if you really want to, missing it out is a convenience. After that initial object creation you would use mystring identically regardless of whether it was user defined or built in. So we can call methods of the class using the instance like: mystring.upper() mystring.split() etc Do you follow things so far? It's important to understand the usage of classes and objects before we start worrying about the internal details. -- 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] string indexing
On 20/01/14 07:37, rahmad akbar wrote: Spir and Peter, thanks for the specifics, super helpful. Alan, super thanks for the general advice, you guys are awesome!! You are welcome, but please don't post an entire digest just to say thanks. It uses up bandwidth and storage unnecessarily and some folks pay by the byte... Delete the unnecessary content. Thanks, Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 4.7.5
On 20/01/2014 01:16, Doug and Riekie Dorman wrote: I think I may have found a bug: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair: pair[1]) pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] Should be: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pairs: pairs[1]) pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] I have increased the size of the two s's to show the problem. Doug What has the name you've given your lambda parameter got to do with the name of your list? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python as Teaching Language
On Sun, Jan 19, 2014 at 02:18:54PM -0500, Keith Winston wrote: On Sun, Jan 19, 2014 at 11:55 AM, Alan Gauld alan.ga...@btinternet.com wrote: It has reached the point that I'm back to looking for a new teaching language. In Python 3 the decision has clearly been made to focus on supporting Python's role as a professional software engineering language at the expense of being a successor to ABC or for use in CP4E etc. That's a fair enough decision but it does mean Python is no longer the easiest option for non Comp Sci beginners. It's not worse than the others but it's no longer clearly superior. (IMHO at least! ) But what else is there? that's the problem :-( Hi Alan, since this is off-topic from it's original thread, but I wanted to respond to it, I popped it into a new thread, I hope you don't mind (original was subject iterators). That's the right thing to do. The usual convention is to change the subject line to Python as a teaching language [Was: iterators] so that it's clear from the subject line that you've spawned a new thread from an existing one. Alan, next year I will be teaching a new unit for our first-year Engineering undergrads using Python as an introduction to programming so I've been thinking about these things quite a lot recently. Any language has features that you can't use in an intro course: so just leave them out! If someone wants to spend lots of time learning Python comprehensively then they can do that later. Thankfully you can do a lot in Python without fully understanding its underbelly. As a case in point I don't plan to teach generators or iterators. I will probably broach that subject as follows: In Python there are many types of objects we can loop over with a for statement. We have already seen examples of this with lists and strings e.g.: a = [4, 2, 5] for x in a: ... print(a, 2*a) 4 8 2 4 5 10 Objects that we can loop over are known as iterable. There are other types of objects that are not iterable such as ints and floats: b = 123 for x in b: ... print(b) TypeError: 'int' object is not iterable Note how the error message tells us that this type of object ('int') is not 'iterable'. We've already seen examples of looping over the lines of a text file. It's common in other programming languages to write something like: f = open('myfile.txt') while True: line = f.readline() if not line: # empty string when we get to the end of the file break print(line.upper()) # Do whatever you want with the line here f.close() # Always close the file when done!!! Looping over the lines of a file is so common though that Python has a more convenient version using the fact that a file object is iterable: f = open('myfile.txt') for line in f: print(line.upper()) f.close() One other thing that we need to know here is that some iterables (e.g. lists and strings) can be looped over multiple times whereas file objects can only be looped over once. If you want to loop over the lines of the file again you need to re-open the file (or seek back to the beginning). I would then go on to relate all of the above to list comprehensions. I don't think I'd bother with talking about iterators/iterables and iter/next except in a more advanced Python course. In that course I would also cover generators and other things but for an intro just skip over it. Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] when is pythondontwritebytecode useful?
Hi, When is setting a PYTHONDONTWRITEBYTECODE environment variable useful? Or set sys.dont_write_bytecode to True? Or start Python with the -B option? I know what it does (http://docs.python.org/2/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE), i.e. no pyc or pyo fiules are written, but WHY is that sometimes a good thing? The only useful scenario I can think of is when you don't have write rights to create pyc files but you want to use a package anyway. Perhaps related: it is possible to import zip files, but no pyc files will be created when you do this. However, I recently opened an EGG file with a zip utility (because I knew egg uses zipimport so it's a zip-like format) and I noticed that there were .pyc files. If the creator of the egg put them there, they'd only be useful if the user uses the exact same Python implementatiopn and version, right? So hoiw can the be there? Regards, Albert-Jan ~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 4.7.5
On 20/01/14 01:16, Doug and Riekie Dorman wrote: I think I may have found a bug: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair: pair[1]) pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] Should be: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pairs: pairs[1]) pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] I have increased the size of the two s's to show the problem. In plain text that doesn't help. However you seem to be confused about what the lambda is doing. pairs.sort(key = lambda p : p[1]) is the same as def somefunc(p): return p[1] pairs.sort(key=somefunc) The parameter to the lambda function is completely separate to the list. It's part of the function definition. It takes on whatever value is passed, in your case it is passed the individual tuples within the list. The name you use is irrelevant. -- 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] Understanding Classes
On 20 January 2014 20:33, Alan Gauld alan.ga...@btinternet.com wrote: On 20/01/14 00:55, Christian Alexander wrote: I would first like to state two things, those being that I am a horrible writer as well as explaining things, but Ill try my absolute best. Everything python is an object. Strings, integers, lists, so on and so forth. In regards to classes and their relativity towards objects, I am at complete standstill. For built in string type objects you do this mystring = 'a new string object' But if String were a user defined class you'd need to do this: mystring = String('a user defined string object') ie. you'd 'call' the class name with the data arguments needed. In fact in Python you can explicitly call str() if you really want to, missing it out is a convenience. After that initial object creation you would use mystring identically regardless of whether it was user defined or built in. So we can call methods of the class using the instance like: mystring.upper() mystring.split() And Christian you can experiment with Alan's examples interactively by running the Python interpreter, for example: $ python Python 2.7.3 (default, Jan 2 2013, 16:53:07) [GCC 4.7.2] on linux2 Type help, copyright, credits or license for more information. mystring = 'a new string object' type(mystring) type 'str' mystring.upper() 'A NEW STRING OBJECT' 'another new string'.upper() 'ANOTHER NEW STRING' 'yet another string'.split() ['yet', 'another', 'string'] exit() Typing in the first line mystring = 'a new string object' creates a string object. Typing in the next line type(mystring) shows that mystring is of type str, which is the built in class for strings. So the mystring object is an instance created from class str. Typing in the next line mystring.upper() shows that the mystring object possesses a built in method named upper() that knows how to return an upper case copy of itself. Typing in the next line 'another new string'.upper() shows that any/every string knows how to do the same thing. Because every string has the same method named upper(). Because every string instance is created from the str class, and the str class defines upper(), so every string inherits this method. Typing in the next line 'yet another string'.split() shows that any/every string has a method named split() that knows how to return a list of individual words in the string. This method is also defined by the str class, and so is inherited by every string. Do you follow things so far? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] when is pythondontwritebytecode useful?
On Mon, Jan 20, 2014 at 02:42:57AM -0800, Albert-Jan Roskam wrote: Hi, When is setting a PYTHONDONTWRITEBYTECODE environment variable useful? Or set sys.dont_write_bytecode to True? Or start Python with the -B option? I know what it does (http://docs.python.org/2/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE), i.e. no pyc or pyo fiules are written, but WHY is that sometimes a good thing? The only useful scenario I can think of is when you don't have write rights to create pyc files but you want to use a package anyway. If you don't have write permissions then it won't write the byte code files anyway. Perhaps related: it is possible to import zip files, but no pyc files will be created when you do this. However, I recently opened an EGG file with a zip utility (because I knew egg uses zipimport so it's a zip-like format) and I noticed that there were .pyc files. If the creator of the egg put them there, they'd only be useful if the user uses the exact same Python implementatiopn and version, right? So hoiw can the be there? The .pyc files will be ignored if the versions don't match. One problem that can occur with the byte-code files is if you try to import them using different interpreters at different times. So let's say you have a module that is regularly imported by Python 2.6 and then you also want to use it in a program that you regularly run with Python 2.7. The two interpreters will fight each other constantly rewriting and stomping over each other's .pyc files. You could use the -B option with one of the interpreters to alleviate this. Truthfully I've never used the option so I'm just guessing though. And in any case Python 3 handles the multiple interpreters problem better with its __pycache__ directory. Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string indexing -- side note, rather OT
On 01/20/2014 01:19 AM, Keith Winston wrote: On Sun, Jan 19, 2014 at 3:50 PM, Alan Gauld alan.ga...@btinternet.com wrote: How would Python know whether you want find for gettext, mmap, str, xml.etree.ElementTree.Element or xml.etree.ElementTree.ElementTree? Absolutely, but a newbie doesn't even guess that more than one find would exist. Or even that there would need to be more than one. That's exactly it. I'm just getting to the point of being able to understand how much I don't know, and (I'm only a little embarrassed to admit) Alan's empty-string example was an ah-ha moment for me. I expect Help will be a great deal more useful now (of course, as I type that I realize I could have used the class name, help(str.find), instead of an impromptu instance. Another little ah-ha). And of course, the instant I understood all that, the point that Mark made became obvious. But I didn't see it before. Side note, rather OT: It is apparently very hard to share the perspective of novices once one gets used to features to the point they have become easy. It seems, in fact, often much harder for programmers than other people (I suspect this is because programmers, or geeks, are often more autistic so to say). Obviously, a talented footballer (soccer) does not consider juggling with a ball (using only feet/head) easy for novices! Some programmers, of which I consider they have a pedagogic spirit, nevertheless are obviously skilled in that, whatever their expertise level. I think this is just normal human skill (sociability, in fact) but our way of life alters or distorts it. Denis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ValueError: could not convert string to float: '13,2'
Not very elegant, but it'll work. I don't suppose there is a function for determining the number of digits after the decimal, is it? It looks like you are trying to avoid rounding errors in decimal arithmetic. You might be interested in Python's decimal.Decimal type then. That's right, I had never heard of decimal.Decimal. I'll check it up. Also, anybody knows the maximum and/or minimum integer python will accept? Integers in Python (*) are unlimited 10**1000 -1 99 99 In practice the amount of available memory will be the limit, but you are unlikely to reach that. (*) Python 2 had int and long where values that could not represented by machine integers were automatically propagated to long. In Python 3 the int and long have been united as int. Thank you very much, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Understanding Classes
On 01/19/2014 10:59 PM, Christian Alexander wrote: Hello Tutorians, Looked all over the net for class tutorials Unable to understand the self argument Attempting to visual classes I have searched high and low, for easy to follow tutorials regarding classes. Although I grok the general concept of classes, I am unable to visually understand what exactly self does, or why it is even necessary. It seems very magic to me. Also I am having the most difficult with the __init__() method in classes, and why that is also required. Keep in mind that I am a visual person (maybe I should have been a graphic designer), therefore most programming concepts flow irritatingly slow for me. Imagine that for an app you had to define 2 persons p1 p2 (maybe game characters for instance). In an imaginary programming language, a definition of p1 could look like this: p1 = {name=Maria, age=33} # no good python code This would be a composite piece of data, made of 2 fields (attributes, properties...). In python there is no such generic type Object or Composite to which such data as p1 could belong. You must define a custom type (class) for them, eg: class Person: pass Now, you can have p1 of type Person, which is written as if you would call the type Person, like a func, to make a new person (this is close to what happens): p1 = Person() Then, one can define fields on it: p1.name = Maria p1.age = 33 print(p1.name, p1.age) We could do the same thing for p2: p2 = Person() p2.name = paulo p2.age = 22 print(p2.name, p2.age) Now, say persons are supposed to do things, and all can do the same things. To define something all persons can do, you would define it on their class (this is the second purpose of a class), eg: class Person: def salute (self): print (Hello, my name is + self.name + and I am + str(self.age) years old.) As you can see, this method uses the attributes 'name' 'age' we manually defined on both p1 p2. Then, how does the method, which is defined on the type, not on individual objects, know where to find these attributes? You are right to say there is some magic at play here. Let us use the method first, before explaining: p1.salute() p2.salute() [Copy-paste run all this code.] On the first call, we ask the method 'salute' to operate on p1, and it writes p1's name age. Same for p2. Inside the method, the attributes are searched on the weird param called 'self'. This is just what happens: when calling a method, the object on which it operates is assigned to the parameter self. 'self' is just a name for the-object-on-which-this-method-operates-now. When it operates on p1, self is p1, thus attributes are searched on p1; same for p2. We need some placeholder because the method is defined on the type and works for any object of this type (any instance). [We can define a method on p1 which works on p1 only. Maybe try it.] Finally, if we define a whole range of persons that way, it is annoying to set all attributes manually. We could define a method, say 'def_attrs', to be called at startup. But python has a specially dedicated method for that, which we don't even need to call explicitely, named '__init__'. We will use it to set person attributes: class Person: def __init__ (self, name, age): self.name = name self.age = age def salute (self): print (Hello, my name is + self.name + and I am + str(self.age) years old.) (yes, init methods typically are as stupid as this; too bad python does not do the mechanical job automagically) And this is used like this: p1 = Person(maria, 33)# no need to call __init__ explicitely p1.salute() p2 = Person(paulo, 22)# ditto p2.salute() denis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] when is pythondontwritebytecode useful?
On Mon, Jan 20, 2014 at 5:42 AM, Albert-Jan Roskam fo...@yahoo.com wrote: When is setting a PYTHONDONTWRITEBYTECODE environment variable useful? Or set sys.dont_write_bytecode to True? Or start Python with the -B option? I know what it does (http://docs.python.org/2/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE), i.e. no pyc or pyo fiules are written, but WHY is that sometimes a good thing? The only useful scenario I can think of is when you don't have write rights to create pyc files but you want to use a package anyway. The bug tracker can provide insight into why a given feature exists, or why it's implemented a certain way: Issue 602345: option for not writing .py[co] files http://bugs.python.org/issue602345 However, I recently opened an EGG file with a zip utility (because I knew egg uses zipimport so it's a zip-like format) and I noticed that there were .pyc files. Eggs are a binary distribution format. They contain byte-compiled .pyc files and extension modules. There's even an option to exclude .py source files. The filename should indicate the Python version and platform. Loading extension modules directly from an egg depends on the pkg_resources module from setuptools. The modules are extracted to a local cache directory. On Windows the default cache directory is %APPDATA%\Python-Eggs, else it uses ~/.python-eggs. You can customize this with the environment variable PYTHON_EGG_CACHE. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] how run it on python 3
this is the coding that i am trying to run it on python 3.3. the original coding was made on python 2.7 however i have made some changes to the coding to make it work on python 3.3. the changes that i have made on brackets and raw_input to input. the coding does not load the external file ans says invalid syntax . please help me thank You very much. the changed coding: # Import statements import random import datetime #Arrays to store the definitions and keywords read from the file keywords=[]; definition=[]; correctAnswer=[]; #Counter for the wrong Answer and counter of number of definition in correctAnswerCounter=0 wrongAnswer=0; counter=0; # Taking User input for accepting the file name to be read filename = (keywords.txt) #Reading the file from start to the end for line in open(filename,'r').readlines(): if(counter%2==0): keywords.append(line); counter=counter+1; correctAnswer.append(0) else: definition.append(line); keys=[]; keys=line.split( ); counter=counter+1; # Running two while loops to make the pattern recursive while True: # Starting the time for quiz and also, creating variables to make sure that same sequences and answers are not repeated a = datetime.datetime.now().replace(microsecond=0) prevWord=0 prevSeq=0 # While loop to run the code till each answer is correctly answered while correctAnswer.count(2)!=(counter/2): #While loop to generate an different random number from one the generated previously while True: word=random.randint(0,(counter/2)-1) if(correctAnswer[word]!=2): break; if(prevWord==word): continue; # Displaying the new keyword each time. print (Please Select the number which is the correct definition of the word:) ,keywords[word] #Generating an new sequence each time different from previous one while True: sequences =random.randint(0,2) if(prevSeq==sequences): continue; else: break #Generating an new incorrect answer each time different from previous one while True: incorrectAnswer=random.randint(0,len(correctAnswer)-1) if(incorrectAnswer==word): continue; else : break #Generating an new incorrect answer each time different from previous one while True: incorrectAnswerSecond=random.randint(0,len(correctAnswer)-1); if (incorrectAnswer==incorrectAnswerSecond): continue if(incorrectAnswerSecond==word): continue else: break # Displaying the options to the user based on the sequence number generated if (sequences==0): print (1.),definition[word] print (2.),definition[incorrectAnswer] print (3.),definition[incorrectAnswerSecond] elif (sequences==1): print (1.),definition[incorrectAnswer] print (2.),definition[incorrectAnswerSecond] print (3.),definition[word] elif (sequences==2): print (1.),definition[incorrectAnswerSecond] print (2.),definition[word] print (3.),definition[incorrectAnswer] #Taking the answer from user answer = input(Enter the Correct Number between 1 to 3) # Assign the seq and word to preseq and word prevSeq=sequences prevWord=word #Checking the answer if they are corret. if(0 == sequences): if(answer == 1): print (success) correctAnswer[word]=correctAnswer[word]+1 correctAnswerCounter=correctAnswerCounter+1 else: print (Wrong Answer) print (Correct Answer: ) ,definition[word] wrongAnswer=wrongAnswer+1; elif(1 == sequences): if(answer == 3): print (success) correctAnswer[word]=correctAnswer[word]+1 correctAnswerCounter=correctAnswerCounter+1 else: print (Wrong Answer) print (Correct Answer: ) ,definition[word] wrongAnswer=wrongAnswer+1; elif(2 == sequences): if(answer == 2): print (success) correctAnswer[word]=correctAnswer[word]+1 correctAnswerCounter=correctAnswerCounter+1 else: print (Wrong Answer) print (Correct Answer: ) ,definition[word] wrongAnswer=wrongAnswer+1 # Stopping the time of the clock b = datetime.datetime.now().replace(microsecond=0) # displaying number of wrong answer and total quiz time print (Total Number of Wrong Answer:), wrongAnswer print (Total Quiz Time), (b-a) print (Total
Re: [Tutor] how run it on python 3
On 1/20/2014 12:51 PM, S Tareq wrote: external file ans says invalid syntax . The full traceback with the invalid syntax message will provide you the specific line where the issue is realized. Note that the actual error my occur elsewhere particularly with mismatched parenthetical expressions, but always include the full traceback as that tells us where to start looking for the issue. Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how run it on python 3
S Tareq wrote: this is the coding that i am trying to run it on python 3.3. the original coding was made on python 2.7 however i have made some changes to the coding to make it work on python 3.3. the changes that i have made on brackets and raw_input to input. the coding does not load the external file ans says invalid syntax . please help me thank You very much. the changed coding: print (Please Select the number which is the correct definition of the word:) ,keywords[word] #Generating an new sequence each time different from previous one while True: print is a function in Python 3. Python 2's statement print Please select..., keywords[word] must be spelt print(Please select..., keywords[word]) You have added the closing parenthesis too early. But you should not translate your scripts by hand -- there's a tool called 2to3 that does the legwork for you. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how run it on python 3 (S Tareq)
Tareq, It'd be nice if you formatted it through upload with gist ( https://gist.github.com/ ) and posted the syntax error you were receiving as well. Then you wouldn't have to put ?s instead of indents, and we'd be able to read it better. I believe this is actually recommended in the mailing list information and rules. Brandon ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how run it on python 3
But you should not translate your scripts by hand -- there's a tool called 2to3 that does the legwork for you. S Tareq has asked this question just a few days ago. https://mail.python.org/pipermail/tutor/2014-January/099466.html Most of us here have not yet gone entirely senile yet, so we still remember. In that thread, we asked the original questioner why they were having difficulty. But S Tareq responded in the way I would expect out of an automated answering machine: that is, not at all. This is not encouraging: either he or she did not understand the question, or they ignored the multiple requests for clarification. In which case, I can only suggest: please read and respond to what other people are asking you. Otherwise, it defeats the purpose of asking a question: that is, to communicate. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how run it on python 3
On 1/20/2014 4:05 PM, Danny Yoo wrote: S Tareq has asked this question just a few days ago. https://mail.python.org/pipermail/tutor/2014-January/099466.html Most of us here have not yet gone entirely senile yet, so we still remember. Speak for yourself! The rest of us are rapidly approaching senility and looking forward to it! You get to meet new people every day and they all like you! :) In that thread, we asked the original questioner why they were having difficulty. But S Tareq responded in the way I would expect out of an automated answering machine: that is, not at all. This is not encouraging: either he or she did not understand the question, or they ignored the multiple requests for clarification. We're continuing this off-line at the moment and I'm reasonably convinced it's not an automated answering machine. And with any luck future posts won't be quite so diluted... Emile In which case, I can only suggest: please read and respond to what other people are asking you. Otherwise, it defeats the purpose of asking a question: that is, to communicate. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how run it on python 3
In that thread, we asked the original questioner why they were having difficulty. But S Tareq responded in the way I would expect out of an automated answering machine: that is, not at all. This is not encouraging: either he or she did not understand the question, or they ignored the multiple requests for clarification. We're continuing this off-line at the moment and I'm reasonably convinced it's not an automated answering machine. And with any luck future posts won't be quite so diluted... Ok. If you do hear back, please keep the rest of the mailing list informed. I was waiting for some kind of response to the thread from last week: https://mail.python.org/pipermail/tutor/2014-January/099591.html and when threads dangle like that, it feels like an unresolved cliffhanger. I do not like cliffhangers. :P ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how run it on python 3
On 21/01/2014 00:05, Danny Yoo wrote: But you should not translate your scripts by hand -- there's a tool called 2to3 that does the legwork for you. S Tareq has asked this question just a few days ago. https://mail.python.org/pipermail/tutor/2014-January/099466.html Most of us here have not yet gone entirely senile yet, so we still remember. In that thread, we asked the original questioner why they were having difficulty. But S Tareq responded in the way I would expect out of an automated answering machine: that is, not at all. This is not encouraging: either he or she did not understand the question, or they ignored the multiple requests for clarification. In which case, I can only suggest: please read and respond to what other people are asking you. Otherwise, it defeats the purpose of asking a question: that is, to communicate. Seems more likely that they didn't like being told not to send flaming great big screen dumps when a couple of lines cut 'n pasted would have been enough. Which I had to look up, but trying to follow the threads on PEPs 460 and 461 was rather hard work and my health isn't the best :( -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor