在 Python 中,您可以随时为对象添加属性。例如:
class Sentence(object):
pass
sentence = Sentence()
sentence.the_string = "This is a sentence."
__init__
方法是在构造类的实例时调用的特殊方法。例如,Sentence()
最终调用__init__
没有额外的参数。因为我没有定义 any __init__
,所以我得到了默认值,它什么都不做。但是现在让我们定义一个,并给它一个额外的参数:
class Sentence(object):
def __init__(self, the_sentence):
pass
sentence = Sentence("This is a sentence.")
sentence.the_string = "This is a different sentence."
现在,唯一剩下的就是将该属性创建移动到__init__
方法中:
class Sentence(object):
def __init__(self, the_sentence):
self.the_string = the_sentence
sentence = Sentence("This is a sentence.")
实际问题是关于将字符串存储在属性而不是属性中。这几乎肯定不是你真正应该学习的内容的一部分,而是表明你的讲师、教科书或教程作者实际上并不十分了解 Python。Aproperty
是一种在方法之上伪造普通属性的方法,您不应该很快学习。