Re: [Tutor] Get/Set/Attribute Accessors in Python?

2012-12-05 Thread eryksun
On Wed, Dec 5, 2012 at 10:38 AM, Malcolm Newsome
 wrote:
>
> One thing I've come across in C# (and, quite frankly, am having a difficult
> time grasping) is Get and Set (Accessors).
>
> Since, I don't ever recall reading about this in Python, I'm wondering if
> they exist.

Python uses what it calls "descriptors" to create bound methods and
handle special properties such as __dict__, __weakref__, and slots
defined by __slots__. You can roll  your own as you see fit. Raymond
Hettinger's guide is a good place to start:

http://docs.python.org/3/howto/descriptor.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Get/Set/Attribute Accessors in Python?

2012-12-05 Thread Mark Lawrence

On 05/12/2012 16:58, Steven D'Aprano wrote:


And here is how it should be written in Python:

class Example(object):
 def __init__(self, value):
 self.x = value


instance = Example(42)
print instance.x  # gives 42
instance.setx(23)




And introduce error handling while we're at it? Should we consider a 
CutAndPasteError in Python? :)


c:\Users\Mark\MyPython>type mytest.py
class Example(object):
def __init__(self, value):
self.x = value


instance = Example(42)
print(instance.x)  # gives 42
instance.setx(23)
c:\Users\Mark\MyPython>mytest.py
42
Traceback (most recent call last):
  File "C:\Users\Mark\MyPython\mytest.py", line 8, in 
instance.setx(23)
AttributeError: 'Example' object has no attribute 'setx'


--
Cheers.

Mark Lawrence.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Get/Set/Attribute Accessors in Python?

2012-12-05 Thread Malcolm Newsome
Thanks gentlemen! Your answers were very thorough and helpful.  I'll play
with this some.

Malcolm Newsome
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expressions question

2012-12-05 Thread eryksun
On Wed, Dec 5, 2012 at 7:13 PM, Ed Owens  wrote:
 str(string)
> '[\nUpdated:
> Dec 5, 2012, 5:08pm EST\n]'
 m = re.search('":\b(\w+\s+\d+,\s+\d+,\s+\d+:\d+.m\s+\w+)<', str(string))
 print m
> None

You need a raw string for the boundary marker \b (i.e the boundary
between \w and \W), else it creates a backspace control character.
Also, I don't see why you have ": at the start of the expression. This
works:

>>> s = 'Updated: Dec 5, 2012, 5:08pm EST'
>>> m = re.search(r'\b(\w+\s+\d+,\s+\d+,\s+\d+:\d+.m\s+\w+)<', s)
>>> m.group(1)
'Dec 5, 2012, 5:08pm EST'

But wouldn't it be simpler and more reliable to use an HTML parser?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unexpected results with obj.method().method()

2012-12-05 Thread eryksun
On Wed, Dec 5, 2012 at 1:11 PM, C M Caine  wrote:
>
> The full code is on pastebin http://pastebin.com/tUh0W5Se
>
 import game
 S = game.State()
 S1 = S.move_state(1).move_state("SWAP")
 S2 = S.move_state(1)
 S3 = S2.move_state("SWAP")
 S1 == S3
> False

In lines 156-160 you change players by mutating the object. You need
to use a local variable such as "next_player" and return State(board,
self.turn_number + 1, next_player).

Also, you're mixing tabs and 2-space indents. Please choose one or the
other. The most popular style is 4-space indents, as recommended by
the PEP 8 style guide.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expressions question

2012-12-05 Thread Brett Ritter
On Wed, Dec 5, 2012 at 5:04 PM, Ed Owens  wrote:

> >>> m = re.search(':\b(\w+\s+\d+,\s+\d+,\s+\d+:\d+.m\s+\w+)<', str(string))
> >>> print m
> None
> >>>
>

Okay, without the double-quote (it wasn't the colon that I was worried
about, it was the double-quote), I believe the issue now is that you have a
space in the string (after the colon), but \b is a zero-width match.

-- 
Brett Ritter / SwiftOne
swift...@swiftone.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expressions question

2012-12-05 Thread Alan Gauld

On 06/12/12 00:24, Brett Ritter wrote:


'[\nUpdated: Dec 5, 2012, 5:08pm EST\n]'
 >>> m = re.search('":\b(\w+\s+\d+,\s+\__d+,\s+\d+:\d+.m\s+\w+)<',

It starts with ":
which doesn't appear in your string.


At the end of Updated:


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expressions question

2012-12-05 Thread Alan Gauld

On 06/12/12 00:13, Ed Owens wrote:

 >>> str(string)
'[\nUpdated: Dec 5, 2012, 5:08pm EST\n]'
 >>> m = re.search('":\b(\w+\s+\d+,\s+\d+,\s+\d+:\d+.m\s+\w+)<',
str(string))
 >>> print m
None
 >>>

I'm sort of embarrassed to ask this, but I've been staring at this
regular expression for hours and can't see why it doesn't work.


When using regex I always try the simplest things first.
Now, I'm not sure how much of the time element you want
but if its just the 'Dec 5, 2012, 5:08pm EST' bit

You can do it thusly:

>>> s = '[\nUpdated: Dec 5, 2012, 5:08pm EST\n]'


>>> m = re.search('Updated:(.+)<', s)
>>> m
<_sre.SRE_Match object at 0x7f48d412d5d0>
>>> m.groups()
(' Dec 5, 2012, 5:08pm EST',)
>>> m.groups()[0].strip()
'Dec 5, 2012, 5:08pm EST'

Now, that might be too simplistic for some of your other scenarios, but 
I'd be inclined to start small and work out rather than trying to be too 
generic too soon.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expressions question

2012-12-05 Thread Ed Owens


On 12/5/12 7:24 PM, Brett Ritter wrote:
On Wed, Dec 5, 2012 at 4:13 PM, Ed Owens > wrote:


>>> str(string)
'[\nUpdated: Dec 5, 2012, 5:08pm EST\n]'
>>> m = re.search('":\b(\w+\s+\d+,\s+\d+,\s+\d+:\d+.m\s+\w+)<',
str(string))
>>> print m
None


It starts with ":
which doesn't appear in your string.
the : is at the end of 'Updated: ', I think.  That did make me think 
about the " in the regular expression above, which I didn't remember. 
Just for completeness, here it is again, as copied:


>>> m = re.search(':\b(\w+\s+\d+,\s+\d+,\s+\d+:\d+.m\s+\w+)<', str(string))
>>> print m
None
>>>

Ed
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unexpected results with obj.method().method()

2012-12-05 Thread Oscar Benjamin
On 5 December 2012 18:11, C M Caine  wrote:
> Dear all,
>
> I've written a class State that subclasses tuple. The class has a method
> move_state that takes a move and returns a new state object representing the
> new state of the game.
>
> I would expect S1 and S3 to be equal on the last line here, but they are
> not.
>
 import game
 S = game.State()
 S1 = S.move_state(1).move_state("SWAP")
 S2 = S.move_state(1)
 S3 = S2.move_state("SWAP")
 S1 == S3
> False
>
> Printing the two states shows that they have very different internal states.
>
 print S1
>  (8, 8, 8, 8, 8, 8, 0)
> 1 0
>  (7, 7, 7, 7, 7, 7, 7)
 print S3
>  (7, 7, 7, 7, 7, 7, 7)
> 0 1
>  (0, 8, 8, 8, 8, 8, 8)

>From your description above I have very little idea what you're trying
to do. You have specified what you were expecting to happen why you're
not happy with what actually happened, which is good. I still don't
understand the problem, though. What is the *relevant* code that
didn't do what you expected?

> If anyone is interested, State represents the state of a 7 7 Kalah board.

I don't know what a Kalah board is.

> The full code is on pastebin http://pastebin.com/tUh0W5Se

You were right not to post this code directly in your email as it's
too big. For the same reason, though, I'm not prepared to read it
through and try to understand the problem.

It would be better if you could trim your problem down to a short
example so that you can then post the full example. An important side
effect of this process is that you will often discover the cause of
the problem yourself before completing your email to the list.

> Are my expectations faulty? (I hope not)
> Have I made some mistake in my code to get these results?

Probably at least one of the above is true, but I can't say much more
than that. Have a read of http://sscce.org/ for some advice about how
to post problems to a mailing list. If you follow the advice there you
will find that
1) You will often be able to solve your problem yourself.
2) If you do post your problem to a mailing list you will be more
likely to get a helpful response.


Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expressions question

2012-12-05 Thread Brett Ritter
On Wed, Dec 5, 2012 at 4:13 PM, Ed Owens  wrote:

> >>> str(string)
> '[\nUpdated: Dec 5, 2012, 5:08pm EST\n]'
> >>> m = re.search('":\b(\w+\s+\d+,\s+\**d+,\s+\d+:\d+.m\s+\w+)<',
> str(string))
> >>> print m
> None
>

It starts with ":
which doesn't appear in your string.

-- 
Brett Ritter / SwiftOne
swift...@swiftone.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Regular expressions question

2012-12-05 Thread Ed Owens

>>> str(string)
'[\nUpdated: Dec 5, 2012, 5:08pm EST\n]'
>>> m = re.search('":\b(\w+\s+\d+,\s+\d+,\s+\d+:\d+.m\s+\w+)<', 
str(string))

>>> print m
None
>>>

I'm sort of embarrassed to ask this, but I've been staring at this 
regular expression for hours and can't see why it doesn't work.  I'm 
trying to recover the date string from the string, with no success.


Thanks in advance for the help.

Ed
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 106, Issue 5

2012-12-05 Thread Alan Gauld

On 05/12/12 21:31, Dave Angel wrote:


That way I can read up from the bottom and get all the others in one
go. I then just delete the rest unread... Thanks to that trick I was


For any email exchange that involves more than two people, you can
easily lose content that way.  Less common, if someone replies twice to
the same message, they won't be captured in the default "final mail".


True, but I've found that by the time I get round to reading them the 
number of cases where the missed message is significant is very low, and 
the time it saves is worth the risk! :-)


And it is the only advantage I've found to top posting!

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] correct way to encode

2012-12-05 Thread Norman Khine
On Wed, Dec 5, 2012 at 3:24 PM, Hugo Arts  wrote:
> On Wed, Dec 5, 2012 at 2:47 PM, Norman Khine  wrote:
>>
>> hello, i have this code from the google fusion table api:
>>
>> (zmgc)☺  python
>> * master 9e4be39 ✗zmgc"
>> Python 2.7.2 (default, Jan 28 2012, 14:53:22)
>> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
>> Type "help", "copyright", "credits" or "license" for more information.
>> >>> import csv
>> >>> import urllib2, urllib
>> >>> request_url = 'https://www.google.com/fusiontables/api/query'
>> >>> query = 'SELECT * FROM 3027809'
>> >>> url = "%s?%s" % (request_url, urllib.urlencode({'sql': query}))
>> >>> serv_req = urllib2.Request(url=url)
>> >>> serv_resp = urllib2.urlopen(serv_req)
>> >>> reader = csv.DictReader(serv_resp)
>> >>> for row in reader:
>> ... print row
>> ...
>> {'Name': 'Portugal', 'Contact': 'i...@zeitgeistportugal.org', 'Link':
>> 'http://www.zeitgeistportugal.org/', 'Location': 'Portugal', 'Type':
>> 'Country', 'Icon': '1'}
>> {'Name': 'Porto', 'Contact': 'po...@zeitgeistportugal.org', 'Link':
>> 'http://porto.zeitgeistportugal.org', 'Location': 'Porto, Portugal',
>> 'Type': 'Region', 'Icon': '2'}
>> {'Name': 'Lisboa', 'Contact': 'lis...@zeitgeistportugal.org', 'Link':
>> 'http://lisboa.zeitgeistportugal.org', 'Location': 'Lisbon, Portugal',
>> 'Type': 'Region', 'Icon': '2'}
>> {'Name':
>> '\xd0\x91\xd1\x8a\xd0\xbb\xd0\xb3\xd0\xb0\xd1\x80\xd0\xb8\xd1\x8f',
>> 'Contact': 'zgeis...@gmail.com', 'Link':
>> 'http://thezeitgeistmovement.bg/', 'Location': 'Bulgaria', 'Type':
>> 'Country', 'Icon': '1'}
>>
>>
>> the table has a mix of charecters:
>>
>> https://www.google.com/fusiontables/DataSource?docid=1epTUiUlv5NQK5x4sgdy1K47ACDTpHH60hbng1qw
>>
>> what will be the correct way to encode the items in each dictionary row?
>>
>
> The data you're getting back is almost certainly encoded in UTF-8. Googling
> around, the csv reader doesn't seem to work well at all when unicode is
> involved, but there are some people around trying to make it work. This
> stackoverflow thread might be helpful:
>
> http://stackoverflow.com/questions/1846135/python-csv-library-with-unicode-utf-8-support-that-just-works
>

thanks, in fact i did not have to do anything special to write the
file to a csv, all the fields are correctly encoded as you say:

import csv
import urllib2, urllib
request_url = 'https://www.google.com/fusiontables/api/query'
query = 'SELECT * FROM 3027809'
url = "%s?%s" % (request_url, urllib.urlencode({'sql': query}))
serv_req = urllib2.Request(url=url)
serv_resp = urllib2.urlopen(serv_req)
reader = csv.DictReader(serv_resp)
c = csv.writer(open("entries.csv", "wb"), delimiter=',',
quotechar='"', quoting=csv.QUOTE_ALL)
for row in reader:
c.writerow(row.values())


> HTH,
> Hugo
>



-- 
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 106, Issue 5

2012-12-05 Thread Dave Angel
On 12/05/2012 04:22 PM, Alan Gauld wrote:
> 
>
>
> PPS.
> There is one advantage to lazy top posting. When I return from
> vacation I sort by subject and only open the most recent in a thread.
> That way I can read up from the bottom and get all the others in one
> go. I then just delete the rest unread... Thanks to that trick I was
> able to "read" 700 emails in two days after returning from a weeks
> holiday.
>

For any email exchange that involves more than two people, you can
easily lose content that way.  Less common, if someone replies twice to
the same message, they won't be captured in the default "final mail".


-- 

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 106, Issue 5

2012-12-05 Thread Alan Gauld

On 05/12/12 20:50, Prasad, Ramit wrote:


Maybe I am in the minority, but the only people I know who regularly
bottom/in-line post are regularly on mailing lists.


This is a bad practice picked up from group-ware tools from the 80s/90s 
which unfortunately called themselves email tools, but didn't follow 
email standards - Lotus Notes and MS Outlook being the most obvious 
culprits.


Unfortunately the corporate universe adopted these tools and many 
people's expectations of "email" were formed using these glorified 
message databases. The result is grossly inefficient use (abuse?) of email.


But Ramit is right, the only people I see using email as it was intended 
are the long-term email users on the internet, the great non-technical 
masses use the standards set by the user defaults of Outlook and Notes.


But that doesn't mean we have to accept gross inefficiency without 
protest. Even at work (using Outlook) I use inline posting as my default 
and one or two others have begun to adopt it too. :-)


PS.
Until recently I insisted on using plain text for my mails too but 
eventually I got so many complaints about my mails being hard to format 
for replies that I've relented and switched to HTML...


PPS.
There is one advantage to lazy top posting. When I return from vacation 
I sort by subject and only open the most recent in a thread. That way I 
can read up from the bottom and get all the others in one go. I then 
just delete the rest unread... Thanks to that trick I was able to "read" 
700 emails in two days after returning from a weeks holiday.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 106, Issue 5

2012-12-05 Thread Dave Angel
On 12/05/2012 03:50 PM, Prasad, Ramit wrote:
> 
>>
>> Not to mention that as social conventions regarding email have moved
>> on--e.g. top posting--for the majority of email users

A bug that somehow convinced people that it was "normal."  So other
implementers copied the bug.



-- 

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 106, Issue 5

2012-12-05 Thread Prasad, Ramit
Steven D'Aprano wrote:
> 
> On Mon, Dec 03, 2012 at 05:56:30PM -0600, Luke Paireepinart wrote:
> 
> > I just wanted to make the observation that, at least in gmail, the default
> > behavior is to hide the entire quoted text behind an innocuous "..."
> > button.
> 
> Good lord, the more I hear about Gmail, the more horrible I discover it
> to be. Why does anyone use this crappy, anti-social product?
> 

I think Gmail is a great product and wish more desktop clients would
act in the same manner. The main problems I have seen with are specific 
to dealing with mailing lists/newsgroup. It [Gmail] happens to be 
aimed at the masses and Python tutors tend not be a part of the masses 
when it comes to technology. :)

Not to mention that as social conventions regarding email have moved
on--e.g. top posting--for the majority of email users, members of 
mailing lists seem to have kept their traditions and habits. I am
not saying there are not valid reasons or that I disagree with
the reasons for mailing lists to keep their method of posting. 
It is just that this behavior does not apply to the average email user.
Even in-line posting tends to be either copied with comments above the
original message or a top post saying to look at the original message 
below for comments in a different color.

Maybe I am in the minority, but the only people I know who regularly
bottom/in-line post are regularly on mailing lists.

~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unexpected results with obj.method().method()

2012-12-05 Thread C M Caine
I edited the output of Lines 109-111 from my source code out of the
interpreter transcripts above, by the by.


On 5 December 2012 18:11, C M Caine  wrote:

> Dear all,
>
> I've written a class State that subclasses tuple. The class has a method
> move_state that takes a move and returns a new state object representing
> the new state of the game.
>
> I would expect S1 and S3 to be equal on the last line here, but they are
> not.
>
> >>> import game
> >>> S = game.State()
> >>> S1 = S.move_state(1).move_state("SWAP")
> >>> S2 = S.move_state(1)
> >>> S3 = S2.move_state("SWAP")
> >>> S1 == S3
> False
>
> Printing the two states shows that they have very different internal
> states.
>
> >>> print S1
>  (8, 8, 8, 8, 8, 8, 0)
> 1 0
>  (7, 7, 7, 7, 7, 7, 7)
> >>> print S3
>  (7, 7, 7, 7, 7, 7, 7)
> 0 1
>  (0, 8, 8, 8, 8, 8, 8)
>
> If anyone is interested, State represents the state of a 7 7 Kalah board.
>
> The full code is on pastebin http://pastebin.com/tUh0W5Se
>
> Are my expectations faulty? (I hope not)
> Have I made some mistake in my code to get these results?
>
> Thanks in advance,
> Colin Caine
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Unexpected results with obj.method().method()

2012-12-05 Thread C M Caine
Dear all,

I've written a class State that subclasses tuple. The class has a method
move_state that takes a move and returns a new state object representing
the new state of the game.

I would expect S1 and S3 to be equal on the last line here, but they are
not.

>>> import game
>>> S = game.State()
>>> S1 = S.move_state(1).move_state("SWAP")
>>> S2 = S.move_state(1)
>>> S3 = S2.move_state("SWAP")
>>> S1 == S3
False

Printing the two states shows that they have very different internal states.

>>> print S1
 (8, 8, 8, 8, 8, 8, 0)
1 0
 (7, 7, 7, 7, 7, 7, 7)
>>> print S3
 (7, 7, 7, 7, 7, 7, 7)
0 1
 (0, 8, 8, 8, 8, 8, 8)

If anyone is interested, State represents the state of a 7 7 Kalah board.

The full code is on pastebin http://pastebin.com/tUh0W5Se

Are my expectations faulty? (I hope not)
Have I made some mistake in my code to get these results?

Thanks in advance,
Colin Caine
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Get/Set/Attribute Accessors in Python?

2012-12-05 Thread Steven D'Aprano

On 06/12/12 02:38, Malcolm Newsome wrote:

Hey Tutors,

Python is/was my first language.  Yet, I've recently begun learning C# for
my new job.

One thing I've come across in C# (and, quite frankly, am having a difficult
time grasping) is Get and Set (Accessors).

Since, I don't ever recall reading about this in Python, I'm wondering if
they exist.  If not, what is the "thinking" behind why they are not
included in the language?


They exist, if you program them. Here's a class with getter and setter 
accessors:

class Example(object):
def __init__(self, value):
self.setx(value)
def getx(self):
return self.x
def setx(self, value)
self.x = value


instance = Example(42)
print instance.getx()  # gives 42
instance.setx(23)



And here is how it should be written in Python:

class Example(object):
def __init__(self, value):
self.x = value


instance = Example(42)
print instance.x  # gives 42
instance.setx(23)


Accessors are methods that you must call to get or set a data value. Some
languages (C# and Java, for example) strongly encourage you to use accessors
instead of exposing the data value directly. Why? "Just in case."

Notice how trivially simple my accessors were? Well, they're not always that
trivial. Often you want the getter to calculate a value, or the setter to
enforce some restriction. Here's a toy example:


class Example(object):
def __init__(self, value):
self.setx(value)
def getx(self):
print "I'm the x value!"
return self.x
def setx(self, value)
if value < 0:
raise ValueError('x must not be negative')
self.x = value


If you just exposed self.x as Python does, you can't perform any calculations
unless you use accessor methods. So Java and C# have the philosophy:

- Some day you might need to do a calculation when getting or setting x.

- But if you expose data attribute x directly to the caller, you are committed
  to *always* exposing x to the caller.

- So you better not expose x directly, you should always use accessor methods,
  just in case some day you need them.


But with Python, you never need accessor methods, because we can wrap attribute
access with methods behind the scene! This work is done using the "property"
function. You start by trivially exposing data attribute x directly to the 
caller:

class Example(object):
def __init__(self, value):
self.x = value


then later on, if you need to turn x into a computed attribute, you
simply use property to wrap some accessor methods with the same name
as the data attribute:

class Example(object):
def __init__(self, value):
self.x = value
@property
def x(self):
print "I'm the x value!"
return self._x  # see below
@x.setter
def x(self, value):
if value < 0:
raise ValueError('x must not be negative')
self._x = value


As far as the caller is concerned, there is no change, she still
writes the same direct attribute code:

instance = Example(42)
print instance.x
instance.x = 23

as before.

Did you notice the mysterious reference to self._x above? That leads
neatly to your next question.



Additionally, a separate, but perhaps related question is that I have not
seen public/private classes in Python.  How might this factor into the
whole accessor scenario?  (Or, am I trying to relate two topics that have
nothing to do with each other?)


Private versus Public (of classes, methods, attributes, whatever) has to
do with information hiding.

Information hiding is a very useful idea in programming. In a nutshell,
you might have a class that promises to provide certain features, the
interface, but everything else is an implementation detail that might
go away if you find a better way to program the class.

For example, everything inside a function -- the local variables -- are
utterly private. The caller cannot peek inside a method and grab the
local variables, they can only see the return result:

def hundred():
x = 25  # this is local to the function and invisible from outside
return x + x + x + x  # but this is exposed publicly

If I now improve this function:

def hundred():
return 100


from the outside you have no way of knowing that local variable x has
disappeared. This is a Good Thing.


This philosophy of hiding implementation details is extended to classes,
methods, and attributes. Hence, languages like C#, C++, Java and others
distinguish between Public and Private attributes. Public attributes are
visible to the caller, private ones are not.

The problem is, like all good things, it is possible to have too much
data hiding. People go mad and make everything private, forcing the caller
to reinvent the wheel. Consequently you will often find programmers
plaintively asking "I need to do foo, and this class does exactly what I
want, but the foo() method is private, how do I get access to it?"

For most languages, it is possible to 

Re: [Tutor] Get/Set/Attribute Accessors in Python?

2012-12-05 Thread Dave Angel
On 12/05/2012 10:38 AM, Malcolm Newsome wrote:
> Hey Tutors,
>
> Python is/was my first language.  Yet, I've recently begun learning C# for
> my new job.
>
> One thing I've come across in C# (and, quite frankly, am having a difficult
> time grasping) is Get and Set (Accessors).
>
> Since, I don't ever recall reading about this in Python, I'm wondering if
> they exist.  If not, what is the "thinking" behind why they are not
> included in the language?

I don't know C#, but it's probably quite similar to Java in these things.

Python doesn't need get and set, because it has a better mechanism.  The
whole idea of get and set in java is that a user of a class shouldn't
make any assumption about internal details of a class.  The user calls
these two functions to read and write a property.  Now, if the
implementor changes his mind about what data format is actually used, he
can still implement the original get and set function interfaces in
terms of the new data fields.

So, you might ask, how does the implementor decide which fields need
such abstraction, and which ones can just be used, safe from likely
change.  Java's answer is that all fields should be wrapped in the
getter and setter paradigm.

In Python, the user of a class uses the data fields in the obvious way. 
Then when the implementor decides that a particular field needs
"abstraction," he doesn't have to make the user change his use.  Instead
the implementor defines those get and set functions, and binds them to
look like a simple field.  That is most easily done by the @property
decorator.



> Additionally, a separate, but perhaps related question is that I have not
> seen public/private classes in Python.  How might this factor into the
> whole accessor scenario?  (Or, am I trying to relate two topics that have
> nothing to do with each other?)
>
>

Python doesn't have any such thing as private classes or private
attributes.  And it doesn't have friends, protected inheritance, etc. 
Instead it's a naming convention, that nobody is supposed to use any
names with a leading underscore.  The theory is that we're all adults here.

Many times in C++ and Java, you need to cheat the private/protected
schemes, to get something tricky accomplished.  One time is when you're
using a library for which you don't have permission to modify the source
of a library.  Another place is in implementing a library, where you
need to follow different rules than the user of the library.  In Python,
instead of cheating (eg. by casting), you just access the item.

I see that Francois has responded while I'm composing this.  Please read
that response as well as mine.

-- 

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Get/Set/Attribute Accessors in Python?

2012-12-05 Thread Francois Dion
On Wed, Dec 5, 2012 at 10:38 AM, Malcolm Newsome
 wrote:
> Hey Tutors,
>
> Python is/was my first language.  Yet, I've recently begun learning C# for
> my new job.

My condolences.

> One thing I've come across in C# (and, quite frankly, am having a difficult
> time grasping) is Get and Set (Accessors).
> Since, I don't ever recall reading about this in Python, I'm wondering if
> they exist.  If not, what is the "thinking" behind why they are not included
> in the language?

Nothing prevents you from creating getter and setter methods for all
your values in your class in Python, but really, you don't need to
most of the time. Refactoring and re-engineering your code later on to
use them if you have to, is pretty much transparent to the rest of the
code.

For example:

class Thing:

colorinfo = "#f00:red"

box = Thing()
print(box.colorinfo)


This will print:
#f00:red

You are happy about how short the code is and start using
box.colorinfo all over the place.

later, you decide, you should have used colorinfo as a method (a
getter, ie getcolorinfo() ) instead of a property, because you want to
add arguments to the constructor and use them in the getter. So you
would then have to go and replace every box.colorinfo by
box.colorinfo(), if you were not using python. But since you are, you
end up doing a getter, and keep the property:

class Thing:
def __init__(self,color,name):
self.color = color
self.name = name

def getcolorinfo(self):
return self.color + ':' + self.name

colorinfo = property(getcolorinfo)

box = Thing("#f00","red")
print(box.colorinfo)
box = Thing("#00f","blue")
print(box.colorinfo)

The output of which is
#f00:red
#00f:blue

The key here is that you are now wrapping the string inside a getter
function, where you could do all kinds of other stuff, but yet, you
never had to modify the print line since it still refers to a property
of the box instance of the Thing object. All because of the property
keyword.
Best of both worlds.

Francois

--
www.pyptug.org  -  raspberry-python.blogspot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Get/Set/Attribute Accessors in Python?

2012-12-05 Thread Malcolm Newsome
Hey Tutors,

Python is/was my first language.  Yet, I've recently begun learning C# for
my new job.

One thing I've come across in C# (and, quite frankly, am having a difficult
time grasping) is Get and Set (Accessors).

Since, I don't ever recall reading about this in Python, I'm wondering if
they exist.  If not, what is the "thinking" behind why they are not
included in the language?

Additionally, a separate, but perhaps related question is that I have not
seen public/private classes in Python.  How might this factor into the
whole accessor scenario?  (Or, am I trying to relate two topics that have
nothing to do with each other?)

Hopefully these questions are clear enough...

Thanks in advance,

Malcolm Newsome
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] correct way to encode

2012-12-05 Thread Hugo Arts
On Wed, Dec 5, 2012 at 2:47 PM, Norman Khine  wrote:

> hello, i have this code from the google fusion table api:
>
> (zmgc)☺  python
> * master 9e4be39 ✗zmgc"
> Python 2.7.2 (default, Jan 28 2012, 14:53:22)
> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import csv
> >>> import urllib2, urllib
> >>> request_url = 'https://www.google.com/fusiontables/api/query'
> >>> query = 'SELECT * FROM 3027809'
> >>> url = "%s?%s" % (request_url, urllib.urlencode({'sql': query}))
> >>> serv_req = urllib2.Request(url=url)
> >>> serv_resp = urllib2.urlopen(serv_req)
> >>> reader = csv.DictReader(serv_resp)
> >>> for row in reader:
> ... print row
> ...
> {'Name': 'Portugal', 'Contact': 'i...@zeitgeistportugal.org', 'Link':
> 'http://www.zeitgeistportugal.org/', 'Location': 'Portugal', 'Type':
> 'Country', 'Icon': '1'}
> {'Name': 'Porto', 'Contact': 'po...@zeitgeistportugal.org', 'Link':
> 'http://porto.zeitgeistportugal.org', 'Location': 'Porto, Portugal',
> 'Type': 'Region', 'Icon': '2'}
> {'Name': 'Lisboa', 'Contact': 'lis...@zeitgeistportugal.org', 'Link':
> 'http://lisboa.zeitgeistportugal.org', 'Location': 'Lisbon, Portugal',
> 'Type': 'Region', 'Icon': '2'}
> {'Name':
> '\xd0\x91\xd1\x8a\xd0\xbb\xd0\xb3\xd0\xb0\xd1\x80\xd0\xb8\xd1\x8f',
> 'Contact': 'zgeis...@gmail.com', 'Link':
> 'http://thezeitgeistmovement.bg/', 'Location': 'Bulgaria', 'Type':
> 'Country', 'Icon': '1'}
>
>
> the table has a mix of charecters:
>
> https://www.google.com/fusiontables/DataSource?docid=1epTUiUlv5NQK5x4sgdy1K47ACDTpHH60hbng1qw
>
> what will be the correct way to encode the items in each dictionary row?
>
>
The data you're getting back is almost certainly encoded in UTF-8. Googling
around, the csv reader doesn't seem to work well at all when unicode is
involved, but there are some people around trying to make it work. This
stackoverflow thread might be helpful:

http://stackoverflow.com/questions/1846135/python-csv-library-with-unicode-utf-8-support-that-just-works

HTH,
Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] correct way to encode

2012-12-05 Thread Norman Khine
hello, i have this code from the google fusion table api:

(zmgc)☺  python
* master 9e4be39 ✗zmgc"
Python 2.7.2 (default, Jan 28 2012, 14:53:22)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> import urllib2, urllib
>>> request_url = 'https://www.google.com/fusiontables/api/query'
>>> query = 'SELECT * FROM 3027809'
>>> url = "%s?%s" % (request_url, urllib.urlencode({'sql': query}))
>>> serv_req = urllib2.Request(url=url)
>>> serv_resp = urllib2.urlopen(serv_req)
>>> reader = csv.DictReader(serv_resp)
>>> for row in reader:
... print row
...
{'Name': 'Portugal', 'Contact': 'i...@zeitgeistportugal.org', 'Link':
'http://www.zeitgeistportugal.org/', 'Location': 'Portugal', 'Type':
'Country', 'Icon': '1'}
{'Name': 'Porto', 'Contact': 'po...@zeitgeistportugal.org', 'Link':
'http://porto.zeitgeistportugal.org', 'Location': 'Porto, Portugal',
'Type': 'Region', 'Icon': '2'}
{'Name': 'Lisboa', 'Contact': 'lis...@zeitgeistportugal.org', 'Link':
'http://lisboa.zeitgeistportugal.org', 'Location': 'Lisbon, Portugal',
'Type': 'Region', 'Icon': '2'}
{'Name': '\xd0\x91\xd1\x8a\xd0\xbb\xd0\xb3\xd0\xb0\xd1\x80\xd0\xb8\xd1\x8f',
'Contact': 'zgeis...@gmail.com', 'Link':
'http://thezeitgeistmovement.bg/', 'Location': 'Bulgaria', 'Type':
'Country', 'Icon': '1'}


the table has a mix of charecters:
https://www.google.com/fusiontables/DataSource?docid=1epTUiUlv5NQK5x4sgdy1K47ACDTpHH60hbng1qw

what will be the correct way to encode the items in each dictionary row?

thanks

norman

-- 
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with web.py error

2012-12-05 Thread eryksun
On Wed, Dec 5, 2012 at 2:13 AM, Erik Martinson  wrote:
>
> File "/usr/lib/python2.7/sqlite3/dbapi2.py", line 63, in convert_date
>  return datetime.date(*map(int, val.split("-")))
>
> ValueError: invalid literal for int() with base 10: '21 01:47:43'
> 127.0.0.1:59850 - - [04/Dec/2012 22:47:35] "HTTP/1.1 GET /" - 500 Internal
> Server Error
>
> I understand the error, there is no way '21 01:47:43' can become an int.
> What I can not figure out is the correlation between the last two lines in
> the traceback. What is actually calling the last command 'datetime.date'?

See the web.py SqliteDB class:

https://github.com/webpy/webpy/blob/master/web/db.py#L1010

Notice it sets 'detect_types'. More here:

http://docs.python.org/2/library/sqlite3.html#module-functions-and-constants
http://docs.python.org/2/library/sqlite3.html#default-adapters-and-converters

The issue then is the "created" field in your todo table is type
"date", but contains a "timestamp".
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor