python - 如何在 Fortran 派生类型或类中实现类型绑定(bind)写入语句输出

标签 python oop fortran derived-types

假设我有这个简单的类:

   Module Foo
        ...
        character(len=3), parameter :: describe_Foo=(/'BAR', 'BED', 'BOD'/)
        ...
        type :: A
            real :: value
            integer :: descriptor
        contains
            procedure :: getter
            procedure :: setter
            ...
        end type A

   contains
        function writetype(self,...)
            ...
            write(writetype,*) self%value, describe_foo(self%descriptor)
        end function writetype
   ...
   end module Foo

我怎样才能将它的接口(interface)定义为“write”,以便每次将此类型传递给 write 语句时,它都会输出由类方法 writetype 定义的字符串。

换句话说,用 Python 的说法,我可以实现与 __str__() 方法等效的方法吗?

我发现诱人的花絮暗示这是可能的,请参阅 User-defined derived-type Input/Output procedures (Fortran 2003) User-defined derived-type Input/Output procedure interfaces (Fortran 2003) .这些文档提供了足够的信息来编写我需要的方法,但我仍然不清楚如何定义接口(interface)或过程规范以便发生我想要的行为。

示例应用:

program test
    ...
    type(A) :: bartype, bedtype
    ...
    bartype=A(120.0,1)
    bedtype=A(102.0,2)
    write(*,*) bartype,bedtype
end program test

期望的输出:

>test.exe
 120.0000 BAR
 102.0000 BED

最佳答案

您需要有一个通用的 WRITE(FORMATTED) 绑定(bind),绑定(bind)到具有合适特征的特定过程。有关详细信息,请参阅 F2008 标准中的第 9.6.4.8 节。

type :: A
  real :: value
  integer :: descriptor
contains
  procedure :: writetype
  generic :: write(formatted) => writetype
end type A
...
subroutine writetype(dtv, unit, iotype, v_list, iostat, iomsg)
  ! Argument names here from the std, but you can name them differently.
  class(A), intent(in) :: dtv         ! Object to write.
  integer, intent(in) :: unit         ! Internal unit to write to.
  character(*), intent(in) :: iotype  ! LISTDIRECTED or DTxxx
  integer, intent(in) :: v_list(:)    ! parameters from fmt spec.
  integer, intent(out) :: iostat      ! non zero on error, etc.
  character(*), intent(inout) :: iomsg  ! define if iostat non zero.
  ...
  write (unit, "(F9.4,1X,A)", IOSTAT=iostat, IOMSG=iomsg)  &
      dtv%value, describe_foo(dtv%descriptor)
end subroutine writetype

可能还值得注意的是,您需要一个实现此功能的编译器!

关于python - 如何在 Fortran 派生类型或类中实现类型绑定(bind)写入语句输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17459763/

相关文章:

python - 如何从任意深度嵌套的字典中删除

带有子例程和函数的 Fortran OpenMP

for-loop - 重新启动 do 循环

function - 具有 Fortran 函数的有组织的库

python - 如何在Pygame中画一条连续的线?

python - 以矢量化方式连接给定开始、结束数字的范围数组 - NumPy

java - 从单独的类获取对象的引用

c++ - 问:如何创建有序的字符串对

非 OOP 程序员的 PHP 框架

python - Tweepy 和 flask : failed to get request token