LoginSignup
0
0

More than 1 year has passed since last update.

[py2rb] 抽象基底クラス

Last updated at Posted at 2022-01-31

はじめに

移植やってます。
( from python 3.7 to ruby 2.7 )

抽象基底クラス (Python)

from collections.abc import Sized

print(isinstance([1, 2], Sized))
print(issubclass(list, Sized))
print(isinstance([], Sized))
print(isinstance(set({1, 2}), Sized))
print(isinstance(3, Sized))
print(isinstance('Hello, world!', Sized))
print(isinstance({'id': 1, 'name': 'John'}, Sized))

# output
True
True 
True 
True 
False
True 
True 

こちらの記事が分かりやすい。

defined? (Ruby)

require 'set'

def sizeable(obj)
  if obj.is_a?(Integer)
    false
  else
    begin
      obj.size
      true
    rescue => exception
      obj.method_defined? :size, true
    end
  end
end

puts sizeable(3)
puts sizeable([])
puts sizeable([1, 2])
puts sizeable(Set.new([1, 2]))
puts sizeable({'id': 1, 'name': 'John'})
puts sizeable('Hello, world!')
puts sizeable(Array)
puts sizeable(Class)

# output
false
true 
true 
true 
true 
true 
true 
false

Integer.sizeってバイト数を返すんですね。

花より団子で。

メモ

  • Python の 抽象基底クラス を学習した
  • 百里を行く者は九十里を半ばとす
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0