Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2015-12-26 Thread malitician
On Saturday, December 26, 2015 at 3:04:45 AM UTC+1, [email protected] wrote:
> #i have worked over 2hours only to get this: some-one help please
> manipulate_data = []
> item = {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}
> manipulate_data.append(item)
> for i in  reversed(manipulate_data):
> new = {"ANDELA", "TIA", "AFRICA"}
> def list_append(manipulate_data, new):
> manipulate_data.append(new)
> return new
> return dict.keys()
>
> 
>  print manipulate_data
> #this is the instruction:
> Create a function manipulate_data that does the following
> Accepts as the first parameter a string specifying the data structure to be 
> used "list", "set" or "dictionary"
> Accepts as the second parameter the data to be manipulated based on the data 
> structure specified e.g [1, 4, 9, 16, 25] for a list data structure
> Based off the first parameter
> 
> return the reverse of a list or
> add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the 
> resulting set
> return the keys of a dictionary.

I am now more confused than before, as beginners like we have stated
earlier, how does this solution applies to the real question ( bank
account )
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread jfong
Ben Finney at 2015/12/26  UTC+8 11:42:08AM wrote:
> The Python FAQ answers this, even using an example the same as yours
> https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value>.
> 
Thank you, Ben. It's amazing that you seem to know every piece of Python 
information hiding in the web:-)

see this question listed in python core language's Q&A makes me feel better for 
I am not the only one who commit this kind of crime. I should read this Q&A 
throughly before going any further.

--Jach
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2015-12-26 Thread malitician
On Thursday, December 24, 2015 at 9:58:54 PM UTC+1, Tim Chase wrote:
> On 2015-12-24 11:36, [email protected] wrote:
> > it is a homework, but we are to figure out the solution first , all
> > we need is some guidance please and not to be spoon fed like many
> > thought 
> 
> Ah, with the intended interface as given by the tests, and the code
> you've already put together, you'll find comp.lang.python is a much
> friendlier place.
> 
> 
> >   def test_invalid_operation(self):
> > self.assertEqual(self.my_account.withdraw(1000), "invalid
> > transaction", msg='Invalid transaction') 
> 
> The test above is failing because your withdraw() method doesn't
> return "invalid transaction" but rather prints it:
> 
> > def withdraw(self, amount):
> > if self.balance>= amount:
> > self.balance  -=  amount
> > else:
> >   print('invalid transaction')
> 
> as gleaned from this error message:
> 
> > [{"message": "Failure in line 23, in test_invalid_operation\n
> > self.assertEqual(self.my_account.withdraw(1000), \"invalid
> > transaction\", msg='Invalid transaction')\nAssertionError: Invalid
> > transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0,
> > "time": "0.80"}}
> 
> The test says "I expected that calling the function would return
> "invalid transaction" but it didn't" (a better test-runner would
> also have let you know that it had returned None)
> 
> Though frankly, I'd consider that a bad test, since it's an
> exceptional condition, so it should be checking that a custom
> InvalidTransactionException was raised.  But sometimes you have to
> work with what you've got.
> 
> -tkc

you and others here saved my days , instead of "RETURN" i have been using 
"PRINT". i never knew the differences earlier . Problem solved , thanks for 
having guys like all of you here. I'm just a week old into python programming 
and i have learned a lot   .Merry xmas
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread jfong
Chris Angelico at 2015/12/26  UTC+8 11:44:21AM wrote:
> Pike is semantically very similar to Python, but it uses C-like
> variable scoping. Here's an equivalent, which might help with
> comprehension:
> 
> function outerf()
> {
> int counter = 55;
> void innerf()
> {
> write("%d\n", counter);
> int counter;
> counter += 1;
> }
> return innerf;
> }
Hi! ChrisA, this is the first time I hear the name "Pike" programming 
language:-)

> Based on that, I think you can see that having a variable declaration
> in the function turns things into nonsense. What you're actually
> wanting here is to NOT have the "int counter;" line, such that the
> name 'counter' refers to the outerf one.
> 
> In Python, assignment inside a function creates a local variable,
> unless you declare otherwise. To make your example work, all you need
> is one statement:
> 
> nonlocal counter
> 
> That'll cause the name 'counter' inside innerf to refer to the same
> thing as it does in outerf.

Thank you for the explanation. It reminds me to dig out something which seems I 
had been read before. It's about nested scope in the book "Learning Python" by 
Mark Lutz.

 "An assignment (X = value) creates or changes the name X in the current local
scope, by default. If X is declared global within the function, the assignment 
creates or changes the name X in the enclosing module's scope instead. If, on 
the other hand, X is declared  nonlocal within the function in 3.X (only), the 
assignment changes the name X in the closest enclosing function's local scope."

I shouldn't forget this:-(
 
> Hope that helps!

You have a correct answer. Thanks again.

--Jach
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread Ben Finney
[email protected] writes:

> Thank you, Ben. It's amazing that you seem to know every piece of
> Python information hiding in the web:-)

You're welcome, I'm glad to help. As for the “hiding”, the answer is in
the Python documentation itself.

> see this question listed in python core language's Q&A makes me feel
> better for I am not the only one who commit this kind of crime.

Never feel embarrassed of not knowing something; we should all be active
on the edge of our own ignorance. The embarrassment would be in not
seeking to improve our understanding.

> I should read this Q&A throughly before going any further.

Searching in the official documentation, and in archives of community
forums, is an essential skill to learn for a programmer. I wish you good
fortune in improving that skill :-)

-- 
 \  “Nothing is more sacred than the facts.” —Sam Harris, _The End |
  `\   of Faith_, 2004 |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread Chris Angelico
On Sat, Dec 26, 2015 at 8:07 PM,   wrote:
> Thank you for the explanation. It reminds me to dig out something which seems 
> I had been read before. It's about nested scope in the book "Learning Python" 
> by Mark Lutz.
>
>  "An assignment (X = value) creates or changes the name X in the current local
> scope, by default. If X is declared global within the function, the 
> assignment creates or changes the name X in the enclosing module's scope 
> instead. If, on the other hand, X is declared  nonlocal within the function 
> in 3.X (only), the assignment changes the name X in the closest enclosing 
> function's local scope."
>

Yep! That's an accurate description of how assignment works.

One of the cool things about Python is that there are all sorts of
things that work _exactly_ the same way. Every one of these statements
is a form of assignment:

import json  # 1
from sys import argv  # 2
def testfiles(files): # 3, 4
failures = 0 # 5
for file in files:  # 6
with open(file) as fp: # 7
try: data = json.load(fp) # 8
except JSONDecodeError as err: # 9
failures += 1 # 10
return failures
count = testfiles(argv) # 11

Okay, every one except the 'return' statement. :)

1: "import x" is basically the same as "x = __import__('x')".
2: "from x import y" is basically "y = __import__('x').y" (more or
less). This grabs "sys.argv" and assigns it to the name "argv".
3: Defining a function constructs a new function object and assigns it
to the name. This is like doing "testfiles = ".
4: As the function gets called, a new scope is created, and inside
that scope, the interpreter does the equivalent of "files = ",
where the magic snags a reference to whatever was used as the argument
(so this is basically "files = argv").
5: That's straight-forward assignment, right there.
6: A 'for' loop grabs an iterator, then repeatedly does "file =
next(iterator)" until there's nothing more to do.
7: A 'with' statement does some work, and then does "fp = " if it has an 'as' clause.
8: Another straight-forward assignment, because I couldn't think of
anything better to use. (Normally you'd lay this out with 'try:' on a
separate line, but then I'd have had a line without any assignment at
all.)
9: Like a 'with' statement, 'except' assigns to its name. There's a
special case here, in that it also does 'del err' at the end of the
except block, to clean stuff up; but it's still just assignment.
10: Augmented assignment is assignment too. x+=1, x-=1, x*=1, etc, are
all assigning to x.
11: Another normal assignment, because otherwise the rest of the work
is pointless. :)

Every one of these follows the standard rules for assignment. For
instance, you could create a function that does a top-level import:

$ python3
Python 3.6.0a0 (default:6e114c4023f5, Dec 20 2015, 19:15:28)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def do_imports():
... global os, sys, json
... import os, sys, json
...
>>> do_imports()
>>> json


You wouldn't normally do this for standard modules like 'os' and
'sys', but if you have something huge to load up (like pandas, or
oauth2client), it might be convenient to use them globally, but load
them conditionally. Since 'import' is a statement, not a declaration,
you can do this!

Python's flexibility and simplicity are a huge part of why I love the
language so much.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2015-12-26 Thread princeudo52
i am really enjoying u guyz, i didnt sleep yesterday night, but all is working 
out well now: i am 2weeks old in python, thanks you all for the assistance 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2015-12-26 Thread princeudo52
@ cameron, are u sure this solution u gave me works
here is what i am getting, i am really having headache, some-one should please 
have mercy:
def manipulate_data(list_data, set_data):
if list_data == ["apples", "orange", "mangoes"]:
for i in reversed(set_data):
return i
elif list_data == {}


and this is the erro:
 File "python", line 5
elif list_data == {}
   ^
SyntaxError: invalid syntax
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2015-12-26 Thread princeudo52
this is what i finally got, i give-up, some-one, any body pls help:
def manipulate_data(list_data, set_data):
if list_data == ["apples", "orange", "mangoes"]:
for set_data in reversed(set_data):
return set_data
elif manipulate_data(list_data == {"apples", "orange", "mangoes"}):
list_data.append("ANDELA", "TIA", "AFRICA")
for set_data in list_data:
return set_data
if manipulate_data(list_data == {"apples": 23, "oranges": 15, "mangoes": 3, 
"grapes": 45}):
return dict.keys()
-- 
https://mail.python.org/mailman/listinfo/python-list


please can i get help on this problem

2015-12-26 Thread Prince Udoka
Create a function manipulate_data that does the following
Accepts as the first parameter a string specifying the data structure to be 
used "list", "set" or "dictionary"
Accepts as the second parameter the data to be manipulated based on the data 
structure specified e.g [1, 4, 9, 16, 25] for a list data structure
Based off the first parameter

return the reverse of a list or
add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the 
resulting set
return the keys of a dictionary.


here is my work, but i dont know what i ave done wrong:
def manipulate_data(list_data, set_data):
if list_data == ["apples", "orange", "mangoes"]:
for set_data in reversed(set_data):
return set_data
elif manipulate_data(list_data == {"apples", "orange", "mangoes"}):
list_data.append("ANDELA", "TIA", "AFRICA")
for set_data in list_data:
return set_data
if manipulate_data(list_data == {"apples": 23, "oranges": 15, "mangoes": 3, 
"grapes": 45}):
return list_data.keys()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: please can i get help on this problem

2015-12-26 Thread Ben Finney
Please help us by choosing a descriptive Subject field. The one you've
chosen tells us *nothing* useful.

As it turns out, I can't get anything useful from your message either:

Prince Udoka  writes:

> here is my work, but i dont know what i ave done wrong:

Neither do I. What is confusing you, in particular? Describe what you're
confused by (for example, what behaviour are you seeing, and how is that
different from what you expect?). Summarise that behaviour in a short
phrase and put it in the Subject field.

-- 
 \“Please to bathe inside the tub.” —hotel room, Japan |
  `\   |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: please can i get help on this problem

2015-12-26 Thread Prince Udoka
gud day sir, please i have an assignment, nd i am just 2weeks in python; i 
tried the code i uploaded but its nt working plz help, i need guidiance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: please can i get help on this problem

2015-12-26 Thread Prince Udoka
sir does this make sense:
def manipulate_data(item, fruits):
if item == ["apples", "oranges", "mangoes", "grapes"]:
for fruits in reversed(item):
return item
elif item == {"apples", "oranges", "mangoes", "grapes"}:
for fruits in item:
fruits.append("ANDELA", "TIA", "AFRICA")
return item
if item ==  {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}:
return dict.keys()

-- 
https://mail.python.org/mailman/listinfo/python-list


Importing constantly changing variables

2015-12-26 Thread ariklapid . swim
Hello everyone !
First of all, excuse me for my horrible English.

I am an electronics engineering student, trying to use raspberry pi for one of 
my projects.
Meanwhile, my goal is simply to create a pair of files, written in python, 
which would do the following:

A file named "sensors.py" imports varying values from physical sensors. These 
values are constantly changing. 
(At this point - I intend to change them manually):

[code]
def import_soilMoisture():
soilMoisture = 40 # Later - Imports value from corresponding RPi's GPIO
return soilMoisture

def import_airTemperture():
airTemperture = 24 # Later - Imports value from corresponding RPi's GPIO
return airTemperture

def import_airHumidity():
airHumidity = 69 # Later - Imports value from corresponding RPi's GPIO
return airHumidity
[/code]

A second file, named "main.py" is intended to import and print the values from 
"sensors.py":

[code]
import time

def main():
while True:
import sensors
print(sensors.import_soilMoisture())
print(sensors.import_airTemperture())
print(sensors.import_airHumidity())
time.sleep(5)
main()
[/code]

As you can see, I want the program to print all values each 5 seconds.
When I run the file "main.py" it does print values every 5 seconds, BUT when I 
manually change
the values (e.g. airTemperture = 30 instead of 24) and save the file, nothing 
changes - 
the old values keep on printing.

[b]Help me please to understand what's wrong[/b]
[i]For who it may concern: My OS is Debian[/i]

Thanks to you all in advance!! :) :D
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Importing constantly changing variables

2015-12-26 Thread Ian Kelly
On Sat, Dec 26, 2015 at 8:14 AM,   wrote:
> As you can see, I want the program to print all values each 5 seconds.
> When I run the file "main.py" it does print values every 5 seconds, BUT when 
> I manually change
> the values (e.g. airTemperture = 30 instead of 24) and save the file, nothing 
> changes -
> the old values keep on printing.

Changing the source code of a module isn't going to affect that module
in a running program if it's already been imported. You can use the
importlib.reload function to force a module to be reloaded, but this
is generally anti-recommended. If not done correctly it can result in
multiple versions of the module being simultaneously in use, leading
to confusing error conditions.

It sounds like you're not trying to update the code anyway, just the
data used in the code. For that, you'd be better off putting the data
in a data file that your "sensors.py" would read from and re-read on
every iteration.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2015-12-26 Thread Cameron Simpson

On 26Dec2015 03:23, [email protected]  wrote:

this is what i finally got, i give-up, some-one, any body pls help:
def manipulate_data(list_data, set_data):
   if list_data == ["apples", "orange", "mangoes"]:
   for set_data in reversed(set_data):
   return set_data
   elif manipulate_data(list_data == {"apples", "orange", "mangoes"}):
   list_data.append("ANDELA", "TIA", "AFRICA")
   for set_data in list_data:
   return set_data
   if manipulate_data(list_data == {"apples": 23, "oranges": 15, "mangoes": 3, 
"grapes": 45}):
   return dict.keys()


It is like you have not read the question at all. To remind you:

 Create a function manipulate_data that does the following
 Accepts as the first parameter a string specifying the data structure to be 
 used "list", "set" or "dictionary"
 Accepts as the second parameter the data to be manipulated based on the data 
 structure specified e.g [1, 4, 9, 16, 25] for a list data structure

 Based off the first parameter ...

So clearly the function must start like this:

 def manipulate_data(kind, data):

and have some kind of decision inside the function, based on the first 
parameter, which will be one of the strings "list", "set" or "dictionary".


Instead, you have written a function above which seems to accept two parameters 
with the first being a list and the second a set.


Perhaps you have not realised that while Python has types, a variable may refer 
to an object of _any_ type. So the "data" parameter in my example above may be 
a list OR a set OR a dictionary. (Or anything else, but you only need to cope 
with those three).


So the function might be called in these ways:

 manipulate_data("list", ["apples", "orange", "mangoes"])

 manipulate_data("set", {"apples", "orange", "mangoes"})

 manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, 
"grapes": 45})

In fact, I suggest you make your test program end with those three calls, so 
that it looks like this (again, untested - this is a framework for you to 
complete):


 def manipulate_data(kind, data):
   if kind == 'list':
 ... do stuff with data using it as a list ...
 ... return the reverse of a list ...
   elif kind == 'set':
 ... do stuff with data using it as a set ...
 ... add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set ...
 ... and return the resulting set ...
   elif kind == 'dictionary':
 ... do stuff with data using it as a dictionary ...
 ... return the keys of a dictionary ...
   else:
 raise ValueError("invalid kind %r, expected 'list', 'set' or 'dictionary'" 
% (kind,))

 manipulate_data("list", ["apples", "orange", "mangoes"])

 manipulate_data("set", {"apples", "orange", "mangoes"})

 manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, 
"grapes": 45})

so that it is a small program which defines your function and then calls it 
three times with different parameters.


Note that where your question says "a list" or "the set" or "a dictionary", it 
is really referring to the "data" parameter, so that is what you should be 
working with.


Cheers,
Cameron Simpson 


https://mail.python.org/mailman/listinfo/python-list


On 26Dec2015 11:09, Cameron Simpson  wrote:

On 25Dec2015 15:05, [email protected]  wrote:

i have gotten the answer of that problem


Please include some context when posting to the list; there are many 
discussions and it is best to include a little more than the subject 
line in such things. It is also polite to post your working solution 
for the benefit of those who have assisted you, or for others with a 
similar problem.


Then two more messages in quick succession: this list is not an 
instant messaging system. Please try to post a single message, with 
your question and also what code you have already.


Regarding your actual question, commentry below the quoted text follows...

On 25Dec2015 15:08, [email protected]  wrote:

Create a function manipulate_data that does the following
Accepts as the first parameter a string specifying the data structure to be used "list", 
"set" or "dictionary"
Accepts as the second parameter the data to be manipulated based on the data 
structure specified e.g [1, 4, 9, 16, 25] for a list data structure
Based off the first parameter

  return the reverse of a list or
  add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the 
resulting set
  return the keys of a dictionary.

#my solution is:
def manipulate_data(dic,dict_data = {'name':'prince','age':21,'sex':'male'}):
return dict_data.keys()

def manipulate_data( alist, list_data = [2,8,16,23,14]):
return list_data.reverse()

def manipulate_data(aset, set_data = {"bee","cee","dee"}):
set_data = {"bee","cee","dee"}
set_data.update("ANDELA","TIA","AFRICA")
return dictionary_data
#please what is wrong with my code


The most obvious thing that is wrong it that you have 3 functions here 
with the same name. In Python that means: define the first func

Re: please can i get help on this problem

2015-12-26 Thread Ben Finney
Prince Udoka  writes:

> sir does this make sense:

Referring to the whole of a community as “sir” is not only too formal,
it also betrays a different error: you seem to think you're in a
one-on-one dialogue devoted to your issues.

Please, instead of trying to make your messages more polite (your
phrasing is already plenty polite enough), do us the respect of spending
time on the *content* of your message.

As has been asked of you many times now: When you have a question,
please make it specific and answerable.

Describe what *specifically* is confusing or concerning you; describe
*specifically* what you did, what you expected to happen, and what
happened instead.

Putting effort into making your messages easiler to comprehend will be
far more polite than merely calling us collectively “sir”. It will have
the added benefit of getting you more useful answers.

-- 
 \  “When cryptography is outlawed, bayl bhgynjf jvyy unir |
  `\  cevinpl.” —Anonymous |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Importing constantly changing variables

2015-12-26 Thread Ben Finney
[email protected] writes:

> Hello everyone !
> First of all, excuse me for my horrible English.

As is often the case with people who make this apology, your English is
far better than most native English speakers can use any other language
:-)

> A file named "sensors.py" imports varying values from physical
> sensors. These values are constantly changing. 

Such values, then, should not be obtained from a Python ‘import’.

Instead, you need to come up with a data transfer protocol, or (more
likely) make use of an existing one. Your running program will make
function calls that get the data from “the outside world” – a file, or a
network interface, or some other input to the program.

So to solve this you will need to know the specifics of how the device
connects to the computer, what interfaces it presents for obtaining the
data at run time, and what Python libraries you can use for accessing
that interface.

-- 
 \   “If you do not trust the source do not use this program.” |
  `\—Microsoft Vista security dialogue |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread jfong
Chris Angelico at 2015/12/26  UTC+8 5:50:07PM wrote:
> 11: Another normal assignment, because otherwise the rest of the work
> is pointless. :)

Thanks for this detailed example. As I had learned so far, Python really take 
"name" seriously, and every meaningful result you got have to assign to a name 
at last. This morning I played some codes on the http://pythonturor.com and 
found out that every objects which was not created at top-level of a module or 
in a class will disappear after import. A very "unusual" view. 

> Python's flexibility and simplicity are a huge part of why I love the
> language so much.

simplicity? Maybe because you are s familiar with Python. It's not to me, 
at least at this moment. Please see my next question follows.

--Jach
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread jfong
Last night I noticed that Python does not resolve name in "def" during import, 
as C does in the compile/link stage, it was deferred until it was referenced 
(i.e. codes was executed). That's OK for Anyway codes has to be debugged sooner 
or later. I just have to get used to this style.

But check these codes, it seems not.
---
x = 1  # a global variable
print(x)

class Test:
x = 4  # a class attribute
print(x)
def func(self):
print(x)

x1 = Test()
x1.x = 41  # a instance's attribute
x1.func()  # it's 1 but 41 was expect:-(


--Jach
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread Chris Angelico
On Sun, Dec 27, 2015 at 3:05 PM,   wrote:
>> Python's flexibility and simplicity are a huge part of why I love the
>> language so much.
>
> simplicity? Maybe because you are s familiar with Python. It's not to me, 
> at least at this moment. Please see my next question follows.
>

I define "simplicity" in terms of the number and complexity of the
rules you have to keep in your head. It's not necessarily the best
thing to do; for instance, a C-style #include directive is *extremely*
simple (it is literally "drop the file contents in at this location"),
but I prefer Python's semantics. On the other hand, PHP's include
directive is *not* simple; in many ways it behaves like C's #include,
but it can't be used inside class definitions, and if used in a
function, some of what it does is at top level and some is inside the
function.

Python's rules for imports (whether they're "import X" or "from X
import Y") include a somewhat complicated definition of search path,
but ultimately, it's a matter of hunting down a module and executing
it (all of it) in its own namespace, and then giving you a reference
to sys.modules["X"] (or sys.modules["X"].Y for a from-import).

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A newbie quesiton: local variable in a nested funciton

2015-12-26 Thread Chris Angelico
On Sun, Dec 27, 2015 at 3:11 PM,   wrote:
> Last night I noticed that Python does not resolve name in "def" during 
> import, as C does in the compile/link stage, it was deferred until it was 
> referenced (i.e. codes was executed). That's OK for Anyway codes has to be 
> debugged sooner or later. I just have to get used to this style.
>
> But check these codes, it seems not.
> ---
> x = 1  # a global variable
> print(x)
>
> class Test:
> x = 4  # a class attribute
> print(x)
> def func(self):
> print(x)
>
> x1 = Test()
> x1.x = 41  # a instance's attribute
> x1.func()  # it's 1 but 41 was expect:-(
> 
>
> --Jach

When you import this module, it runs all top-level code. So the
'print' at the top will happen at import time.

Among the top-level statements is a class definition. When that gets
run (to construct the class itself - distinct from instantiating it,
which happens further down), it builds a class by executing all the
statements in it, in order. That results in that value of x being
printed, and then defines a function.

The function definition is being run at time of class construction,
and it creates a new attribute on the Test class. At that time, the
function body isn't actually executed (as you might expect). However,
it's worth noting that the function does not inherit class scope. The
unadorned name 'x' references the global. If you want to access
class-scope names from inside methods, you need to say 'self.x', which
also applies to instance attributes. That's what would do what you
expect here.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list