Reputation: 65
I'm not sure what's the correct style of initializing list with a default value. I'm talking about variable self.privileges. Is this a correct approach? Thanks
class Privileges():
"""privileges class"""
def __init__(self):
self.privileges = ["can add post" , "can delete post" , "can ban user"]
def show_privileges(self):
print(self.privileges)
Upvotes: 1
Views: 81
Reputation: 37489
The two places to define defaults for a class are generally as a class attribute, or in the __init__
method as an instance attribute.
If all instances of the class share the same default value, you can make it a class attribute
class Privileges():
privileges = ["can add post" , "can delete post" , "can ban user"]
def show_privileges(self):
print(self.privileges)
If it's something that will often be different from instance to instance, you can just make it an instance attribute
class Privileges():
def __init__(self):
self.privileges = ["can add post" , "can delete post" , "can ban user"]
Note that using a class attribute doesn't preclude you from adding an instance attribute at some point with the same name, which will override the default class attribute.
class Privileges():
privileges = ['can add post']
def show_privileges(self):
print(self.privileges)
def set_better_privileges(self):
self.privileges = ["can add post" , "can delete post" , "can ban user"]
--
>>> p = Privileges()
>>> p.show_privileges()
['can add post']
>>> p.set_better_privileges()
>>> p.show_privileges()
["can add post" , "can delete post" , "can ban user"]
>>> p2 = Privileges()
>>> p2.show_privileges()
['can add post']
An Advantage of using class attributes for defaults is that it allows you to read the defaults without having to instantiate the class first, and it also allows you to change the defaults for all instances of that class. Just be aware of the behavior, because depending on how your class instances use and modify those variables, you could be inadvertently modifying the default shared across all instances of that class, instead of just for that instance.
Upvotes: 1