You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的Person类中为含last_name的对象添加随机字符串

Solution: Add Random Strings to Person Names with Last Name

First, let's fix the minor issues in your original code before implementing the required logic:

  • You're missing import random and import string at the top (those modules are needed for the random generator)
  • The print statement has a missing closing parenthesis

Now, let's implement the feature you want. We'll create a helper function to modify the name field based on its type (string or list), then apply this to any Person object that has a non-null last_name.

Here's the complete working code with explanations:

import random
import string

class Person:
    def __init__(self, name, last_name=None, age=None):
        self.name = name
        self.last_name = last_name
        self.age = age

def random_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for x in range(size))

def add_random_to_name(person, random_size=10, random_chars="6793YUIO"):
    # Only process if the person has a last_name
    if person.last_name is not None:
        random_str = random_generator(random_size, random_chars)
        # Handle string-type name: convert to list with original + random string
        if isinstance(person.name, str):
            person.name = [person.name, random_str]
        # Handle list-type name: insert random string between first and second element
        elif isinstance(person.name, list) and len(person.name) >= 2:
            person.name.insert(1, random_str)

def main():
    foo = Person('foo', 'food', 10)
    bar = Person(['bar', 'car'], 'dar', 20)
    
    # Apply the random string addition logic
    add_random_to_name(foo)
    add_random_to_name(bar)
    
    print(foo.name)  # Example output: ['foo', 'I76997Y37O']
    print(bar.name)  # Example output: ['bar', 'OUO9UOUU3U', 'car']

if __name__ == "__main__":
    main()

Key Details:

  • The add_random_to_name function only modifies Person objects that have a valid last_name value, which matches your requirement.
  • It handles both string names (converts them to a two-element list) and list names (inserts the random string between the first and second elements of the list).
  • You can customize the random string by adjusting random_size (length) and random_chars (allowed characters) when calling the helper function.
  • We kept your original random_generator function since it already works perfectly for generating the required random strings.

If you need to handle edge cases like lists with more than two elements or other data types for name, you can extend the helper function with additional type checks and logic.

内容的提问来源于stack exchange,提问作者Matan Ran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:52:55