类里定义的变量叫类属性,类里定义的方法叫类方法;类属性分:
1.公有属性:普通属性
2.私有属性:以“_”或"__"开头的属性称为私有属性,私有属性也可以被继承和访问。
例如:
class Info(object):
_name = '春田'
__age = 4
if __name__ == '__main__':
i = Info()
print(i._name) # 输出:春田
print(Info._name) # 输出:春田
print(Info._Info__age) # 输出:4
print(i.__age) # 输出:AttributeError: 'Info' object has no attribute '__age'
print(Info.__age) # 输出:AttributeError: 'Info' object has no attribute '__age'
_name属性:外部通过“Info._name"或“对象._name"访问。
__age属性:外部只能通过“Info._Info__age"访问。
3.__dict__方法:
3.1类调用类本身的__dict__属性,返回的是一个类的属性和方法的字典。
3.2实例对象调用对象本身的__dict__属性,返回的是一个实例对象的属性和方法的字典。
class Info(object):
_name = '春田'
__age = 4
def run(self):
print('run')
if __name__ == '__main__':
i = Info()
i.gender = 'male'
# 调用对象的__dict__方法:{'gender': 'male'}
print(i.__dict__)
# 调用类的__dict__方法:
# {'__module__': '__main__', '_name': '春田', '_Info__age': 4,
# 'run': <function Info.run at 0x7f84a00a0d30>,
# '__dict__': <attribute '__dict__' of 'Info' objects>,
# '__weakref__': <attribute '__weakref__' of 'Info' objects>, '__doc__': None}
print(Info.__dict__)
可以看出:在类被创建的时候,Python会自动给类添加{'__dict__': <attribute '__dict__' of 'Info' objects>, '__weakref__': <attribute '__weakref__' of 'Info' objects>, '__doc__': None}这些属性,但是我们并不需要这些属性,如果这个类被实例化很多对象,那么就会浪费很多的内存空间来存储这些我们不需要的属性,加大了性能开销。如何解决?
通过内置属性:__slots__来限制类可被定义的属性,解决类被自动添加属性的问题。
__slots__属性:slots属性不能被继承
1.指定类对象能绑定的属性;
2.限制属性;
3.节约内存:定义了__slots__属性后,那么该对象不会自动生成__dict__属性。
通过在类中定义__slots__属性来覆盖默认的__dict__行为;__slots__声明接收一个实例变量序列,并在每个实例中只保留足够保存每个变量值的空间,因此不会为每个实例创建__dict__,所以节省空间。
class Test(object):
# 通过__slots__限制类可以存在的属性,slots属性不能被继承
__slots__ = ['name', 'age']
def __init__(self, name, age, gender):
self.name = name
self.age = age
# self.gender = gender # __slots__中未包括此gender属性,所以会报错
class Case(object):
# 测试平台创建测试用例
__slots__ = ['case_id', "title", "url", "data", "expected"]
def __init__(self):
self.case_id = None
self.title = None
self.url = None
self.data = None
self.expected = None
if __name__ == '__main__':
t = Test('春田', "4", 'male')
# 查看类的__dict__方法,发现类的属性和方法里已经没有了__dict__的内容了。
print(Test.__dict__) # {'__module__': '__main__', '__slots__': ['name', 'age'], '__init__': <function Test.__init__ at 0x7f81200a0d30>, 'age': <member 'age' of 'Test' objects>, 'name': <member 'name' of 'Test' objects>, '__doc__': None}
print(t.__dict__) # AttributeError: 'Test' object has no attribute '__dict__'
print(t.age)
print(t.name)
print(t.gender)
# 输出:AttributeError: 'Test' object has no attribute 'gender'