Why have different when Change Lists Global and Variable Global in Python 2.7.9?

时间:2015-05-12 22:18:40

标签: python python-2.7

I have 2 example below, and my question is: why List public class MyButtonTemplate : System.Web.UI.ITemplate { public void InstantiateIn(System.Web.UI.Control container) { Button button = new Button(); button.CommandName = "choice"; button.DataBinding += new EventHandler(Button_DataBinding); container.Controls.Add(button); container.Controls.Add(new LiteralControl("<br />")); } } static void Button_DataBinding(object sender, System.EventArgs e) { Button button = (Button)sender; RepeaterItem repeaterItem = (RepeaterItem)button.NamingContainer; button.ID = "button" + (repeaterItem.DataItem as Choice).id.ToString(); button.CommandArgument = (repeaterItem.DataItem as Choice).id.ToString(); button.Text = (repeaterItem.DataItem as Choice).description; } void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { List<Choice> choiceList = new List<Choice>(); // ... code to fill the list ... Repeater1.ItemTemplate = new MyButtonTemplate(); Repeater1.DataSource = choiceList; Repeater1.DataBind(); } } void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e) { int idx = int.Parse( e.CommandArgument.ToString() ); // this function is NOT called } don't need L to change value like variable global, I think, more Safe if V need L to change

Example 1:

global

Result 1:

L=[1,2,3,4]  
V=5          
def U():
    L[1]=22
    V=55
U()
print L[1]
print V

Example 2:

22
5

Result 2:

L=[1,2,3,4]  
V=5          
def U():
    L[1]=22  
    global V   #Now V will change like L[1]
    V=55
U()
print L[1]
print V

1 个答案:

答案 0 :(得分:1)

Perhaps someone can explain it better than me, but when you do the following:

append/3

Python knows this variable isn't defined in your functions scope, and so it checks the global scope, and prints it.

If you were to do instead

print V

Python knows this variable isn't defined in your functions scope, so it goes ahead and creates it (now it over-shadows V=5 at the global scope). There is different behaviour between writing a variable and reading it.

Now compare this to a list:

V

This is similar to L[1]=22 . Why? Because Python needs to find where L is defined in memory, and then modifies its second index. This is a print V followed by a read, whereas write is simply a print V from memory.

When your operation needs to do a read first, it will find the reference that was defined at the outer scope, and that is why you see a difference between read and V=55.

When your operation is a L[1]=22 first, it will create a new variable in the function scope unless you have that variable marked as a write. Then it will modify that global instead.