Python - Class Variables and Value Dictionary

Suppose I have a class that represents an object that has many properties (simple data types such as strings and integers). Should they be represented as instance variables or is it better to "pythonic" put them in a dictionary?

For instance:

class FruitBasket:
    def __init__(self,apples, oranges, bananas, pears): #number of apples, oranges etc...
        self.apples = apples
        self.oranges = oranges
        self.bananas = bananas
        self.pears = pears



class FruitBasket:
    def __init__(self, fruits): #fruits is a dictionary
        self.fruits = fruits
+4
source share
4 answers

, , , , . FruitBasket , , , . (, ), .

. , (, self.pears). , , , __init__. , , , . __init__, .

, , , , . , , , , , , (self.apples, self.oranges ..). , , , , , . . , , , , "" (, self.pears), , (, self.__init__, self.basketColor, self.basketSize ..).

, , , , - , , (, dict), .

+6

, . , , . , .

, . , .

, , : .

0

, python 3.4 enum! . https://docs.python.org/3/library/enum.html

from enum import Enum
animal = Enum('Animal', 'ant bee cat dog')
animal.ant
0
source

This and very similar questions have been asked many times before, and there are various implementations AttrDict.

However, you should ask yourself if you have any reason not to use the dict. If you do not, then you may need to use a voice recorder. A class that does not have methods probably should not be a class at all. You should also consider the fact that not all valid key keys are valid attribute names.

0
source

All Articles