python创建一个对象的语法_创建一个 Python 对象。

创建一个 Python 对象。

创建 Python® 对象 pyObj 的语法如下:

pyObj = py.modulename.ClassName(varargin)

其中 varargin 是由 ClassName 中的 __init__ 方法指定的构造函数参数列表。

在 MATLAB® 中,Python 对象是引用类型(句柄对象),并且不遵从 MATLAB 的“赋值时复制”和“传值”规则。当您复制句柄对象时,只会复制句柄并且旧句柄和新句柄都引用相同的数据。当您复制 MATLAB 变量(值对象)时,变量数据也会复制。更改原始变量并不会影响新变量。

以下示例在 Python 标准库 textwrap 模块中创建 TextWrapper 类的一个对象。

读取构造函数签名 __init__。

py.help('textwrap.TextWrapper.__init__')

Help on method __init__ in textwrap.TextWrapper:

textwrap.TextWrapper.__init__ = __init__(self, width=70, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True) unbound textwrap.TextWrapper method

创建一个默认 TextWrapper 对象。您不需要传递任何输入参数,因为每个参数都有由等号 (=) 字符标识的默认值。

tw = py.textwrap.TextWrapper;

tw =

Python TextWrapper with properties:

width: 70

subsequent_indent: [1x1 py.str]

wordsep_simple_re_uni: [1x1 py._sre.SRE_Pattern]

fix_sentence_endings: 0

break_on_hyphens: 1

break_long_words: 1

wordsep_re_uni: [1x1 py._sre.SRE_Pattern]

initial_indent: [1x1 py.str]

expand_tabs: 1

replace_whitespace: 1

drop_whitespace: 1

要更改某个逻辑值,例如 break_long_words 属性,请键入:

tw.break_long_words = 0;

要更改某个数值,例如 width 属性,请先确定数值类型。

class(tw.width)

ans =

int64

默认情况下,当您将 MATLAB 数字传递给 Python 函数时,Python 将其作为浮点数读取。如果函数需要的是整数,Python 可能会引发错误或产生意外的结果。将 MATLAB 数字显式转换为整数。例如,键入:

tw.width = int64(3);

阅读 wrap 方法的帮助。

py.help('textwrap.TextWrapper.wrap')

Help on method wrap in textwrap.TextWrapper:

textwrap.TextWrapper.wrap = wrap(self, text) unbound textwrap.TextWrapper method

wrap(text : string) -> [string]

Reformat the single paragraph in 'text' so it fits in lines of

no more than 'self.width' columns, and return a list of wrapped

lines. Tabs in 'text' are expanded with string.expandtabs(),

and all other whitespace characters (including newline) are

converted to space.

从输入 T 创建换行的列表 w。

T = 'MATLAB® is a high-level language and interactive environment for numerical computation, visualization, and programming.';

w = wrap(tw,T);

whos w

Name Size Bytes Class Attributes

w 1x1 112 py.list

将 py.list 转换为元胞数组并显示结果。

wrapped = cellfun(@char, cell(w), 'UniformOutput', false);

fprintf('%s\n', wrapped{:})

MATLAB®

is

a

high-

level

language

and

interactive

environment

for

numerical

computation,

visualization,

and

programming.

尽管 width 为 3,但将 break_long_words 属性设置为 false 会覆盖显示中的 width 值。

相关示例

详细信息


版权声明:本文为weixin_39557813原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。