强化训练:第四篇
问题来源
面向对象的语言的重要特性是存在类的概念
内容
- 新式类和旧式类
- 定义类的属性和“访问权限”
- 类的方法
- 继承:代码复用
- 特殊方法定制类
1.
新式和旧式类:python2中存在差异,python3中无差异
class OldStyle:
name = "OldStyle"
class NewStyle(object):
name = "NewStyle"
print(type(OldStyle))
print(dir(OldStyle))
print((OldStyle.name))
print(type(NewStyle))
print(dir(NewStyle))
print(NewStyle.name)
2.
类的属性和“访问权限”
本质上python语言并没有访问限制。
访问权限通过遵循一定的属性和方法命名规约达到这个效果。
_name
:约定单下划线是该类的内部实现
__name
:双下划线会使得访问名称变为:_classname__name
class NewStyle(object):
name = "NewStyle" # 所有类的对象访问
def __init__(self, email, age, grade):
self.email = email
self._age = age
self.__grade = grade
def get_age(self):
return self._age
def get_grade(self):
return self.__grade
one = NewStyle("[email protected]", 24, 9)
print(one.__dict__) # 获取构造函数中的属性
print(one.get_age())
print(one.get_grade())
#{'_age': 24, 'email': '[email protected]', #'_NewStyle__grade': 9}
#24
#9
3.
类的方法
- 函数是代码块,直接调用
- 方法从属于类
- 装饰器@classmethod # 以类名的方式访问
- 装饰器@property # 以属性的方式访问
class NewStyle(object):
name = "NewStyle" # 所有类的对象访问
def __init__(self, email, age, grade):
self.email = email
self._age = age
self.__grade = grade
@classmethod
def get_age(cls):
return cls.name
@property
def get_grade(self):
return self.__grade
one = NewStyle("[email protected]", 24, 9)
print(one.__dict__) # 获取构造函数中的属性
print(NewStyle.get_age())
print(one.get_grade)
4.
继承:代码复用
- 调用属性和方法
- super()调用父类方法
- 类名调用父类方法
- 子类的类型判断:isinstance, issubclass
- 多继承:
class A(object):
def __init__(self, name, age):
self._name = name
self.__age = age
class B(A):
def __init__(self, name, age, email):
super(B, self).__init__(name, age)
self.__email = email
new_b = B("xiewei", 24, "[email protected]")
print(new_b.__dict__)
print(issubclass(B, A))
#{'_A__age': 24, '_B__email': '[email protected]', #'_name': 'xiewei'}
#True
5.
特殊方法定制类
class Main(object):
"""
Learn python :
"""
name = "Main"
def __init__(self, name, email, age=24):
self.name = name
self.age = age
self.email = email
def __str__(self): # 实例化显示一个有意义的输出
return ('{0}::->>>{1}::->>>{2}'.format(self.name, self.email, self.age))
__repr__ = __str__
def __add__(self, other): # 实现类的加法
return self.__class__(self.name +" 1 " + other.name, self.email + " 2 " + other.email, self.age +other.age)
def __iadd__(self, other):
self.name += other.name
self.email += other.email
self.age += other.age
return self
def __mul__(self, num): # 实现类的乘法
if isinstance(num, int):
return self.__class__(self.age *num, self.email *num, self.name *num)
main1 = Main('xiewei', email="[email protected]")
main2 = Main("weixie", "[email protected]", 32)
print(main1)
print(main2)
main1 += main2
print(main1)
print(main1*2)
#xiewei::->>>[email protected]::->>>24
#weixie::->>>[email protected]::->>>32
#xieweiweixie::->>>[email protected]@shu.edu.cn::->>>56
#112::->>>[email protected]@[email protected]@shu.edu.cn::->>>xieweiweixiexieweiweixie
6.
类, 实例及其他对象的内建函数
- hasattr()
- getattr()
- setattr()
- delattr()
- vars()
obj.__dict__
class MagicMethod(object):
"""how can i become strong."""
name = "MagicMethod"
def __init__(self, name, email):
self.name = name
self.email = email
# def __doc__(self):
# return "This is test."
magicmethod = MagicMethod("xiewei", "[email protected]")
print(magicmethod.__doc__) # 类文档
print(vars(magicmethod)) # 类的属性及其值
print(magicmethod.__dict__) # 类的属性及其值
print(hasattr(magicmethod, 'name')) # 判断是否有属性值 name
print(hasattr(magicmethod, "email")) # 判断是否有属性值 email
print(getattr(magicmethod, "name")) # 获取属性name的值
print(getattr(magicmethod, "email")) # 获取属性email的值
setattr(magicmethod, "email", "[email protected]_copy") # 设置属性值
print(vars(magicmethod))
delattr(magicmethod, "name") # 删除属性name及其值
print(vars(magicmethod))
参考:[python cookbook]