How do I dynamically create properties in Python?

后端 未结 2 621
囚心锁ツ
囚心锁ツ 2020-12-14 18:46

Suppose I have a class like this:

class Alphabet(object):
     __init__(self):
         self.__dict = {\'a\': 1, \'b\': 2, ... \'z\': 26}

     @property
            


        
2条回答
  •  暖寄归人
    2020-12-14 19:17

    Don't do that. Just let the consumers of the class at the __dict directly and trust them not to screw it up. Remember, we're all consenting adults here!

    Ned Batchelder explains better than I can:


    Keep data out of your variable names

    The question reminded me of others I've seen on Stack Overflow or in the #python IRC channel:

    • How do I see if a variable exists?
    • How do I use a variable as the name of another variable?
    • How do I use a variable as part of a SQL table name?

    The thing all these have in common is trying to bridge the gap between two domains: the data in your program, and the names of data in your program. Any time this happens, it's a clear sign that you need to move up a level in your data modeling. Instead of 26 lists, you need one dictionary. Instead of N tables, you should have one table, with one more column in it.

提交回复
热议问题