In JavaScript, I like to define my variables in objects so that it is clear (to me, at least) that all of it's properties are related.
For example:
var box = {
width: 100,
height: 200,
weight: 80
}
Is there a way to do something similar in python?
This is called a dict or dictionary in python the syntax is almost identical:
box = {
'width': 100,
'height': 200,
'weight': 80
}
you can later access these values like this:
box['width']
Grouping using the dictionary is only one of the ways to do it. If you like a.b
attribute access syntax more, you could use one of the following:
You could do it using the module, for example put them to something named settings.py
:
width = 100
height = 200
weight = 80
Then you could use it like this:
import settings
area = settings.width * settings.height
But modules in Python are singletons, so if you change settings.width
in one place - it will change in all the others.
Also you could do grouping using class attributes:
class Box:
width = 100
height = 200
weight = 80
print(Box.width) # 100
# You could use instances to update attributes on separate instance
box = Box()
print(box.width) # 100
box.width = 10
print(box.width) # 10
# But their original values will still be saved on class attributes
print(Box.width) # 100
Another option is to use collections.namedtuple
.
from collections import namedtuple
Box = namedtuple('Box', ('width', 'height', 'weight'))
box = Box(100, 200, 80)
print(box.width) # 100
# Tuples are immutable, so this is more like a way to group constants
box.width = 10 # AttributeError: can't set attribute
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With