python - 函数成为"未绑定的方法"。为什么?

时间:2018-01-18 12:15:01

标签: python

我想创建一个python类来封装一些全局变量:

 <ListView x:Name="listview" SeparatorVisibility="None" 
          HasUnevenRows="True" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid  Margin="10">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <BoxView  Grid.Column="0" Color="Green"/>
                    <StackLayout Grid.Column="1" Padding="20, 10">
                        <Label  Text="{Binding LoremIpsum}"
                        HorizontalOptions="Start"/>
                        <Label  Text="{Binding LoremIpsum1}" />

                        <Label  Text="{Binding LoremIpsum2}" />
                    </StackLayout>
                </Grid>                    
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

跑步时我得到:

class TestEnvironment(object):
    _on_out = None
    # ...

    @staticmethod
    def onOut():
        return TestEnvironment._on_out

    @staticmethod
    def setOnOut(on_out):
        TestEnvironment._on_out = on_out

# -------------------------------------------------------------------- #

def log(msg, process = None):
    print msg

# -------------------------------------------------------------------- #

if __name__ == '__main__':
    TestEnvironment.setOnOut(log)
    print log
    print TestEnvironment.onOut()    
    TestEnvironment.onOut()("A test")

似乎当我将<function log at 0x7fd7738122a8> <unbound method TestEnvironment.log> ... TypeError: unbound method log() must be called with TestEnvironment instance as first argument (got str instance instead) 设置为log时,它变为未绑定的方法。

我怎样才能超越它?

1 个答案:

答案 0 :(得分:1)

修改

删除我的答案是它不再相关(问题似乎已经改变)。 无论哪种方式 - 在Python 3.6上运行代码似乎都有效:

<textarea>

这是一种让它在Python 2.7中运行的方法:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

<function log at 0x7f2787e0a488>
<function log at 0x7f2787e0a488>
A test

查看this question