如何在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 randomandimport stringat the top (those modules are needed for the random generator) - The
printstatement 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_namefunction only modifiesPersonobjects that have a validlast_namevalue, 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) andrandom_chars(allowed characters) when calling the helper function. - We kept your original
random_generatorfunction 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
相关产品推荐
相关产品推荐

