Home >Backend Development >Python Tutorial >Python syntactic sugar to generate identical instances of the same class?

Python syntactic sugar to generate identical instances of the same class?

WBOY
WBOYforward
2024-02-08 23:12:26666browse

Python syntactic sugar to generate identical instances of the same class?

Question content

Suppose I have this simple class:

class person:
    def __init__(self, name, id):
        self.name = name
        self.id = id

and the following examples:

tom = person('tom', 12)
dick = person('dick', 14)
harry = person('harry', 16)

But I want users of my module to be able to create multiple instances of these people without having to call the person constructor, since name and id should Declared in only one location.

Options:

  1. Use copy or deepcopy. This will provide the functionality I need, but every time I want to use tom I have to remember to create a copy of him. This is too bulky.

  2. Create tom Class

class Tom(Person):
    def __init__(self):
        super().__init__('Tom', 12)

This is a little cleaner because every time I want a new tom I can just do tom(), but that requires a lot of code to write and isn't very dry.

Is there any other syntactic sugar in python that would make this kind of thing easier?


Correct Answer


I think this is a good use case for the factory/registry type pattern. The idea is to implement an alternative convenience constructor for classes and a single registry dictionary that stores the configuration corresponding to a given tag. Take a look at the following example:

person_registry = {
    "tom": {"name": "tom", "id": 12},
    "jerry": {"name": "jerry", "id": 13},
    "dick": {"name": "dick", "id": 14},
}


class person:
    def __init__(self, name, id):
        self.name = name
        self.id = id

    @classmethod
    def from_tag(cls, tag):
        """create a person from a tag"""
        if tag not in person_registry:
            raise valueerror(f"not a valid tag {tag}, choose from {list(person_registry)}")
        
        return cls(**person_registry[tag])
    
print(person.from_tag("tom"))

Now you can import the person class and create instances from the shorter tags, while the actual data is stored in one place, the person_registry dictionary. If you want to reduce verbosity, you can also Use positional arguments, but keyword arguments are often preferable because they are more explicit (python's zen).

The beauty of this pattern is that it is actually scalable. So the user can extend the person_registry dictionary, for example:

from persons import Person, PERSON_REGISTRY

PERSON_REGISTRY["liz"] = {"name": "elizabeth", "id": 23}

liz = Person.from_tag("liz")

I hope this helps.

The above is the detailed content of Python syntactic sugar to generate identical instances of the same class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete