Python: Why is embedded tuple shared

时间:2017-08-30 20:53:11

标签: python namedtuple

I do not understand the following behavior of nested named tuples in Python (3.6):

import socket
server_hostname = 'MyServer'

if socket.gethostname() == server_hostname:
    #Remote environment
else:
    #Local environment    

When I create two instances of the Small tuple:

// White to Blue
LinearGradientBrush WhiteBlue = new LinearGradientBrush();
WhiteBlue.StartPoint = new System.Windows.Point(0, 0);
WhiteBlue.EndPoint = new System.Windows.Point(1, 0);
WhiteBlue.GradientStops.Add(new GradientStop(Color.FromArgb(255, 255, 255, 255), 0)); // white
WhiteBlue.GradientStops.Add(new GradientStop(Color.FromArgb(255, 255, 0, 0), 1)); // blue

rectangle1.Fill = WhiteBlue;

// Transparent to Black
LinearGradientBrush Black = new LinearGradientBrush();
Black.StartPoint = new System.Windows.Point(0, 0);
Black.EndPoint = new System.Windows.Point(0, 1);
Black.GradientStops.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 0)); // transparent
Black.GradientStops.Add(new GradientStop(Color.FromArgb(255, 0, 0, 0), 1)); // black

rectangle2.Fill = Black;

they are distinct as I expect

<Rectangle x:Name="rectangle1"
           HorizontalAlignment="Left"
           Width="255"
           Height="255"
           VerticalAlignment="Top">
</Rectangle>

<Rectangle x:Name="rectangle2"
           HorizontalAlignment="Left"
           Width="255"
           Height="255"
           VerticalAlignment="Top">
</Rectangle>

However, when I create two instances of the Outer tuple

class Small(NamedTuple):
   item: float = 0.0

class Outer(NamedTuple):
   zz = Small(item=random())

they will share the a = Small() b = Small() print(a is b) print(a, b) field:

False
Small(item=0.0) Small(item=0.0)

Why? How can I prevent it? (If I used a list instead of a float, and added an element to one instance, it would obviously be in both of them)

0 个答案:

没有答案