class Student(object):
pass
May = Student() # 新建May实例
print(May) 可以看到,变量May指向的就是一个Student的object,后面的0x006C4770是内存地址,每个object的地址都不一样,而Student本身则是一个类。
可以自由地给一个实例变量绑定属性,比如,给实例 May 绑定一个 name 属性,这个 name 属性是实例 May 特有的,其他新建的实例是没有 name 属性的
1 class Student(object):
2 pass
3 May = Student() # 新建May实例
4 print(May)
5 May.name = "May" # 给实例 May 绑定 name 属性为 "May"
6 print(May.name)
7 Peter = Student() # 新建Peter实例
8 # print(Peter.name) # 报错,因为Peter没有Name属性
那么,如果我们需要类必须绑定属性,那如何定义呢? 请参见下文。
1 class Student(object):
2 def __init__(self, name, score):
3 self.name = name
4 self.score = score
5
6 May = Student("May",90) # 须要提供两个属性
7 Peter = Student("Peter",85)
8 print(May.name, May.score)
9 print(Peter.name, Peter.score)
__del__ 析构函数
Just like the __init__ method, there is another special method __del__ which is called when an object is going to die i.e. it is no longer being used and is being returned to the computer system for reusing that piece of memory.
The __del__ method is run when the object is no longer in use and there is no guarantee when that method will be run. If you want to explicitly see it in action, we have to use the del statement which is what we have done here.
相对于 构造函数 Python 也有类似 C++ 中的析构函数 __del__ , Python的垃圾回收过程与常用语言的不一样,如果一定需要,最好需要使用del语句来激活。
私有变量
Note for C++/Java/C# Programmers
All class members (including the data members) are public and all the methods are virtual in Python.
One exception: If you use data members with names using the double underscore prefix such as __privatevar, Python uses name-mangling to effectively make it a private variable.
Thus, the convention followed is that any variable that is to be used only within the class or object should begin with an underscore and all other names are public and can be used by other classes/objects. Remember that this is only a convention and is not enforced by Python (except for the double underscore prefix).