0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

はじめに

移植やってます

self.extend (Python)

class xlist (list):
    def add(self, *args):
        self.extend(args)

class xint (int):
    def add(self, value):
        self += value

x = xlist([1,2,3])
print (x)
x.add (4, 5, 6)
print (x)

x = xint(10)
print (x)
x.add (2)
print (x)

# [1, 2, 3]
# [1, 2, 3, 4, 5, 6]
# 10
# 10

selfに直接extend+ってできるんですね。

どうする? (Ruby)

class Xlist < Array
  def initialize(*args)
    args.each do |x|
      self << x
    end
  end

  def add(*args)
    args.each do |x|
      self << x
    end
  end
end

class Xint < Array
  def initialize(*args)
    args.each do |x|
      self[0].nil? ? self[0] = x : self[0] += x
    end
  end

  def add(*args)
    args.each do |x|
      self[0] += x
    end
  end
end

x = Xlist.new(1, 2, 3)
p x
x.add(4, 5, 6)
p x

x = Xint.new(10)
p x[0]
x.add(2)
p x[0]

# [1, 2, 3]
# [1, 2, 3, 4, 5, 6]
# 10
# 12

トリッキーですが、何とかできました。

メモ

  • Python の self.extend を学習した
  • 道のりは遠そう
0
0
3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?