Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python class keyword arguments

Tags:

python

I'm writing a class for something and I keep stumbling across the same tiresome to type out construction. Is there some simple way I can set up class so that all the parameters in the constructor get initialized as their own name, i.e. fish = 0 -> self.fish = fish?

class Example(object):
    def __init__(self, fish=0, birds=0, sheep=0):
        self.fish = fish
        self.birds = birds
        self.sheep = sheep
like image 229
Ashiataka Avatar asked Sep 01 '25 09:09

Ashiataka


2 Answers

Short answer: no. You are not required to initialize everything in the constructor (you could do it lazily), unless you need it immediately or expose it (meaning that you don't control access). But, since in Python you don't declare data fields, it will become difficult, much difficult, to track them all if they appear in different parts of the code.

More comprehensive answer: you could do some magic with **kwargs (which holds a dictionary of argument name/value pairs), but that is highly discouraged, because it makes documenting the changes almost impossible and difficult for users to check if a certain argument is accepted or not. Use it only for optional, internal flags. It could be useful when having 20 or more parameters to pass, but in that case I would suggest to rethink the design and cluster data.

In case you need a simple key/value storage, consider using a builtin, such as dict.

like image 165
Stefano Sanfilippo Avatar answered Sep 04 '25 11:09

Stefano Sanfilippo


For Python 3.7+, you can try using data classes in combination with type annotations.

https://docs.python.org/3/library/dataclasses.html

Import the module and use the decorator. Type-annotate your variables and there's no need to define an init method, because it will automatically be created for you.

from dataclasses import dataclass

@dataclass
class Example:
    fish: int = 0
    birds: int = 0
    sheep: int = 0
like image 33
aris Avatar answered Sep 04 '25 12:09

aris