user3208597
user3208597

Reputation: 111

Variables connected by dots python

I am very new to Python and really enjoy it. Nevertheless, while going through some code I have trouble understanding why some variables are connected by dots.

Here are some examples taken out of the same file.

class Room(object):

    def __init__(self, name, description):
        self.name = name
        self.description = description
        self.paths = {}

    def go(self, direction):
        return self.paths.get(direction, None)

    def add_paths(self, paths):
        self.paths.update(paths)

and

def test_room():
    gold = Room("GoldRoom",
                """This room has gold in it you can grab. There's a
                door to the north.""")
    assert_equal(gold.name, "GoldRoom")
    assert_equal(gold.paths, {})

The things I do not understand are the ones with the dot so self.paths.update(paths) or self.description and so on.

I don't know why this is used, which variables have to be connected and when I have to use it.

Upvotes: 1

Views: 127

Answers (1)

mgilson
mgilson

Reputation: 310069

They are "attributes". See the tutorial.

In short, I assume you're familiar with dictionaries:

dct = {'foo': 'bar'}
print dct['foo']

Attributes behave very similary for classes:

class Foo(object):
    bar = None

f = Foo()
f.bar = 'baz'
print f.bar 

(In fact, typically, this is a dictionary lookup on a class instance). Of course, once you understand that, you realize that this doesn't just go for classes -- It works for modules and packages too. In short, . is the operator that gets an attribute from something (or sets it, depending on the context).

Upvotes: 5

Related Questions