use*_*597 1 python variables properties
我是Python的新手,非常喜欢它.然而,在执行某些代码时,我无法理解为什么某些变量通过点连接.
以下是从同一文件中取出的一些示例.
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)
Run Code Online (Sandbox Code Playgroud)
和
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, {})
Run Code Online (Sandbox Code Playgroud)
我不明白的事情是用点这样的人self.paths.update(paths)
或 self.description
等.
我不知道为什么要使用它,必须连接哪些变量以及何时必须使用它.
它们是"属性".请参阅教程.
简而言之,我假设您熟悉词典:
dct = {'foo': 'bar'}
print dct['foo']
Run Code Online (Sandbox Code Playgroud)
类的行为非常相似:
class Foo(object):
bar = None
f = Foo()
f.bar = 'baz'
print f.bar
Run Code Online (Sandbox Code Playgroud)
(实际上,通常,这是对类实例的字典查找).当然,一旦你理解了这一点,你就会意识到这不仅适用于类 - 它也适用于模块和包.简而言之,.
是运算符从某个东西获取属性(或根据上下文设置它).
归档时间: |
|
查看次数: |
90 次 |
最近记录: |