简体   繁体   中英

Appending to a instance (for a class list attribute)

What's the most Pythonic way to write the below append statement:

class MyClass():
    my_list = None

    def __init__(self):
        self.attr_a = 'whatever_a_is'
        # NOTE below is commented out here because it's
        # NOT needed by most instances:
        # self.my_list = []


my_class_instance= MyClass()
# Append 'a_certain_value' to list attribute if it exists
# else create it:
if my_class_instance.my_list:
    my_class_instance.my_list.append('a_certain_value')
else:
    my_class_instance.my_list = ['a_cetain_value']

Thanks for the help.

When the class is initialised, it sets my_list = None . It would be better to set my_list = [] , so that the caller can simply append to the list without worrying if it exists or not. This is far more pythonic than what you currently have.



PS

A suggestion for future code to make it more "Pythonic" is to replace if my_class_instance.my_list with if my_class_instance.my_list is not None like so:

 if my_class_instance.my_list is not None: my_class_instance.my_list.append("a_certain_value") else: my_class_instance.my_list = ["a_certain_value"] 

If i get it write, you don't want to set my_list attribute at initialization but only at the first append use ?

A way to do it is to build a custom append method that do the job and are transparent for user :

class MyClass:

    def __init__(self):
        # do something here
        pass

    def custom_append(self, a_certain_value):
        if hasattr(self, 'my_list'):
            self.my_list.append(a_certain_value)
        else:
            self.my_list = [a_certain_value]


my_class_instance = MyClass()

my_class_instance.custom_append('a_certain_value')

But there is few cases where you do not want to initiate my_list to an empty list at instance creation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM