Python Class 变量的作用域?

Python Class Variables' scope?

我正在学习Python(我的背景是C,C++)。

在以下来自 tutorialspoint.com 的代码中:

class Employee:
   'Common base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

(1) 我的困惑在于实例变量 'self.name'、self.salary'。我知道 Pythons 中的变量不需要像 C 那样的显式声明,但是这些变量如何在方法 'displayEmployee' 中使用,难道它们没有自己的局部作用域吗?构造方法'_ init _'?此外,此 'self' 变量是正在创建的 class 的对象 - 因此这意味着 Python 中的 class 的声明也会创建 class 的对象 class(所以没有像 C++ 中那样的虚拟 class)同时存在?

(2) 我的第二个(不太重要的)问题是在上面的代码中,随机放置的字符串“This would create first object of Employee class”和“This would create second object of Employee class", 不显示错误?据我所知,评论必须以#或'''开头?还是字符串在 Python 中也被视为空格?

  1. 创建对象(即 Emplyee() 调用 __init__() 方法,初始化程序)。然后具有 self 参数的所有方法都采用该对象的 实例 进行操作。这意味着这些方法将可以访问该对象的 self 变量。这意味着 static 方法无法访问 this,以及为什么访问这些实例变量不会出错。例如,这会出错:
class Employee:
    def __init__(self):
        self.variable = 123

    @staticmethod # Decorator to indicate this method should not accept 'self'
    def static_method():
        print(self.variable)

因为方法 static_method() 不对 Employee 对象的初始化实例进行操作。

  1. 与任何其他未分配的变量一样,字符串将被解释然后丢弃。像下面这样:
123
"test"
[1, 2]

这些都什么都不做,但考虑到它们是技术上有效的语句,它们不会导致错误。你会经常在文档字符串中看到这种类型的语句,比如:

"""
Long string goes here.
"""