Python-相当于Ruby新方法

时间:2019-02-15 07:15:31

标签: python ruby

我正在尝试在Python中实现以下内容:

NAMES = {"fn" => ["James", "John", "John"], "ln" => ["Smith", "Johnson", "Brown"]}

class RandomNameGenerator
  def self.generate
    new.to_s
  end

  def initialize
    @fn = NAMES['fn'].sample
    @ls = NAMES['ln'].sample
  end

  def to_s
    @fn + " " + @ls
  end
end

哪个返回:

>> RandomNameGenerator.generate
=> "James Smith"
>> RandomNameGenerator.generate
=> "John Johnson"

到目前为止,我的代码如下:

import random

NAMES = {"fn": ["James", "John", "John"], "ln": ["Smith", "Johnson", "Brown"]}

class RandomNameGenerator(object):
    @classmethod
    def generate(cls):
        RandomNameGenerator().__str__

    def __init__(self):
        self.fn = random.choice(NAMES["fn"])
        self.ln = random.choice(NAMES["ln"])

    def __str__(self):
       return self.fn + " " + self.ln
>>> RandomNameGenerator.generate()
>>> print(RandomNameGenerator.generate())
None

我觉得Ruby的new.to_s与Python的RandomNameGenerator().__str__不同。我不明白什么?

2 个答案:

答案 0 :(得分:3)

您不会在generate方法中返回任何内容。初始化类时,也会调用__init__代码,以防您不这样做。您只是在调用类的静态方法。为了使您的代码正常工作,您必须在generate方法中创建RandomNameGenerator的新实例。

class RandomNameGenerator(object):
    @classmethod
    def generate(cls):
        return cls()

    def __init__(self):
        self.fn = random.choice(NAMES["fn"])
        self.ln = random.choice(NAMES["ln"])

    def __str__(self):
       return self.fn + " " + self.ln

答案 1 :(得分:2)

您没有从方法generate()返回:

import random

NAMES = {"fn": ["James", "John", "John"], "ln": ["Smith", "Johnson", "Brown"]}

class RandomNameGenerator(object):
    @classmethod
    def generate(cls):
        return str(cls())

    def __init__(self):
        self.fn = random.choice(NAMES["fn"])
        self.ln = random.choice(NAMES["ln"])

    def __str__(self):
       return self.fn + " " + self.ln

for i in range(5):
    print(RandomNameGenerator.generate())

输出:

John Johnson
John Brown
James Johnson
James Brown
James Johnson