简体   繁体   中英

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM