python中的类,变量混乱

ZCJ*_*ZCJ 0 python class

所以我正在学习课程.为什么我不能使用第三个代码块来执行与第二个代码块明显相同的操作?为什么我必须分配p1,person()而不是仅仅person()按照我在第三个代码块中的方式使用?

#class
class person:
def asdf(self):
    self.firstname=""
    self.lastname=""
    self.id=""
    self.email=""
    self.friends=[]

#second block of code

p1 = person()
p1.firstname="Dave"
p1.lastname="Johnson"
p1.id="2345239"
p1.email="dave@gmail.com"
print p1.firstname

#third block of code

person().firstname="Dave"
person().lastname="Johnson"
person().id="2345239"
person().email="dave@gmail.com"
print person().firstname
Run Code Online (Sandbox Code Playgroud)

MBy*_*ByD 5

在第二个块中,您可以更改同一实例的属性.

p1 = person()               # create new instance
p1.firstname="Dave"         # change its first name
p1.lastname="Johnson"       # change its last name
# ...
print p1.firstname          # access its firstname
Run Code Online (Sandbox Code Playgroud)

在第三个块中,您将在每一行中创建一个新实例.

person().firstname="Dave"      # create new instance and change its firstname
person().lastname="Johnson"    # create new instance and change its lastname
# ...
print person().firstname       # create new instance and access its firstname
Run Code Online (Sandbox Code Playgroud)

为了更准确,问题只发生在最后一行,因为您尝试访问尚未声明的attirbute,因为该firstname属性仅在函数中声明asdf,或者在第二个块中在行中声明p1.firstname="Dave"

这是一个简单的例子:

>>> class A:
...     def AA(self):
...         self.a = 1
... 
>>> a = A()
>>> a.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'a'
>>> a.a = 1
>>> a.a
1
Run Code Online (Sandbox Code Playgroud)