ironpython clr_IronPython: import clr

IronPython: import clr

09/25/2007

2 分钟可看完

本文内容

clr is an IronPython built-in module, which provides some functionalities in order to interop with .NET. When writing "import clr" in a python module, it means you intend to leverage the .NET libraries. One classical example is python string's methods. In IronPython, python type str is implemented by the .NET type System.String. We can call System.String's methods on string objects after the line of "import clr" (see the example below); of course those python string methods are still available.

> ipy.exe

IronPython console: IronPython 2.0 (2.0.0.00) on .NET 2.0.50727.1378

Copyright (c) Microsoft Corporation. All rights reserved.

>>> s = "IronPython"

>>> s.upper()

'IRONPYTHON'

>>> s.ToUpper()

Traceback (most recent call last):

File , line 0, in ##14

File , line 0, in _stub_##15

AttributeError: 'str' object has no attribute 'ToUpper'

>>> import clr

>>> s.upper()                 # python method still works

'IRONPYTHON'

>>> s.ToUpper()               # works

'IRONPYTHON'

Such context change is per-python-module. Although lib.py (below) imports the clr module and app.py then imports the lib module, app.py will not see the .NET methods. Running this app.py under C-Python will fail (ImportError) due to the usage of the clr module in lib.py. But if we make lib.py platform-neutral next time, we are ensured that no change in app.py is needed in order to run it under both C-Python and IronPython.

# lib.py

import clr

def my_upper(s): return s.ToUpper()

# app.py

import lib

s = "hello world"

print lib.my_upper(s)        # print "HELLO WORLD"

#print s.ToUpper()           # AttributeError would throw

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值