无法更新Python对象属性

时间:2019-12-30 15:35:24

标签: python string function return-value function-composition

我正在执行https://exercism.io中的一些任务。不幸的是,由于没有这个老师的反馈,所以决定在这里提问。

基本思想是,您有一个可以使用随机名称启动的机器人,但是在“重置”调用中,随机生成的名称将被替换为新名称,并遵循相同的模式-2个大写随机字符,后跟3个随机整数,例如FV566。

import string
import random

albphabet = string.ascii_uppercase
already_generated_names = []

class Robot:

    def __init__(self):
        self.name = self._generate_random_name()
        print(self.name)

    def reset(self):
        self.name = self._generate_random_name()
        print("Inside reset " + str(self.name))

    def _generate_random_name(self, uppercase_letters_number=2, number_of_digits=3):
        result = ""

        for i in range(0, uppercase_letters_number):
            result += random.choice(albphabet)

        for j in range(0, number_of_digits):
            result += str(random.randint(0, 9))

        if not self._is_name_already_used(result):
            already_generated_names.append(result)
            print("I am about to return " + result)
            return result

        self._generate_random_name()

    def _is_name_already_used(self, n):
        return n in already_generated_names

我面临的麻烦是在调用reset()函数时,该值被分配给self.name = None,而我希望是上面匹配的模式。

import unittest
import random

from robot_name import Robot


class RobotNameTest(unittest.TestCase):
    # assertRegex() alias to adress DeprecationWarning
    # assertRegexpMatches got renamed in version 3.2
    if not hasattr(unittest.TestCase, "assertRegex"):
        assertRegex = unittest.TestCase.assertRegexpMatches

    name_re = r'^[A-Z]{2}\d{3}$'

    def test_has_name(self):
        self.assertRegex(Robot().name, self.name_re)

    def test_name_sticks(self):
        robot = Robot()
        robot.name
        self.assertEqual(robot.name, robot.name)

    def test_different_robots_have_different_names(self):
        self.assertNotEqual(
            Robot().name,
            Robot().name
        )

    def test_reset_name(self):
        # Set a seed
        seed = "Totally random."

        # Initialize RNG using the seed
        random.seed(seed)

        # Call the generator
        robot = Robot()
        name = robot.name
        # Reinitialize RNG using seed
        random.seed(seed)

        # Call the generator again
        robot.reset()
        name2 = robot.name
        self.assertNotEqual(name, name2)
        self.assertRegex(name2, self.name_re)


if __name__ == '__main__':
    unittest.main()


-------------------------------------------- Captured stdout call --------------------------------------------
I am about to return FV566
FV566
I am about to return CP146
Inside reset None
======================================== 1 failed, 3 passed in 0.08s =========================================

C:\Users\Me\Exercism\python\robot-name>python -m pytest robot_name_test.py

我的预期行为是,一旦在reset()内调用generate_random_name(),generate_random_name()将返回一个分配给该名称的字符串,而我最终得到None值。

0 个答案:

没有答案