Python支持面向对象编程,对于一个class类,具有两种类型的成员,一种是变量,另一种是方法(也就是我们平常所说的函数)。所谓的类,指的就是同一个类型的事物,是一个抽象的概念;而所谓实例,就是这个类型中的其中一样具体的事物。
假设我有这样一个类:
class A:
test='this is the test' # 类变量
def __init__(self, name, age):
self.name = name # 实例变量
self.__age = age # 私有变量
接下来我将逐一解释这些变量的含义
对变量来说:
类变量:
顾名思义,类所具有的变量,也就是说它是这个类所有事物的共性,因此即使我们不生成实例,也可以直接通过类来访问这个变量
>>> A.test
'this is the test'
但是无法通过类名对实例变量和私有变量进行访问(因为这俩哥们是属于某个特定的实例的)
>>> A.name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'A' has no attribute 'name'
>>> A.age
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'test' object has no attribute 'age'
实例变量:
实例变量是某个实例所具备的特有的属性,因此我们必须先创建一个实例,再给它的实例变量赋值,每一个实例都可以拥有值不同的实例变量(但每一个实例的类变量都是相同的)因为这是属于每一个实例的特性
>>> a=A('sakura',18) # 创建实例
>>> a.test # 访问类变量
'this is the test'
>>> a.name # 访问实例变量
'sakura'
但此时私有变量依旧无法访问(毕竟这是人家的隐私…)
>>> a.age
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'age'
私有变量:
私有变量是一种特殊的实例变量,它是属于实例的隐私,因为外部无法直接访问,如果想要访问,有两种方案:
- 可以通过类内部写一个函数来间接地返回这个私有变量的值
class A:
test='this is the test' # 类变量
def __init__(self, name, age):
self.name = name # 实例变量
self.__age = age # 私有变量
def get_age(self): # 间接返回私有变量的值
return self.age
>>> a=A('sakura',18)
>>> a.get_age()
18
- 可以用类似作弊的方法强制性地“偷窥人家的隐私":
实例名._类名__私有变量名
class A:
test='this is the test' # 类变量
def __init__(self, name, age):
self.name = name # 实例变量
self.__age = age # 私有变量
>>> a._A__age
18
欢迎关注微信公众号”Sakura的知识库“,一起入门Python人工智能机器学习