Python 强化训练:第四篇

2017-02-08 16:25
1159

强化训练:第四篇

问题来源

面向对象的语言的重要特性是存在类的概念

内容

  1. 新式类和旧式类
  2. 定义类的属性和“访问权限”
  3. 类的方法
  4. 继承:代码复用
  5. 特殊方法定制类

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("xie_wei_sh@foxmail.com", 24, 9)
print(one.__dict__)    # 获取构造函数中的属性
print(one.get_age())
print(one.get_grade())
#{'_age': 24, 'email': 'xie_wei_sh@foxmail.com', #'_NewStyle__grade': 9}
#24
#9

3.

类的方法

  1. 函数是代码块,直接调用
  2. 方法从属于类
  3. 装饰器@classmethod # 以类名的方式访问
  4. 装饰器@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("xie_wei_sh@foxmail.com", 24, 9)
print(one.__dict__)    # 获取构造函数中的属性
print(NewStyle.get_age())
print(one.get_grade)

4.

继承:代码复用

  1. 调用属性和方法
  2. super()调用父类方法
  3. 类名调用父类方法
  4. 子类的类型判断:isinstance, issubclass
  5. 多继承:
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, "xie_wei_sh@foxmail.com")
print(new_b.__dict__)
print(issubclass(B, A))
#{'_A__age': 24, '_B__email': 'xie_wei_sh@foxmail.com', #'_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="xie_wei_sh@foxmail.com")
main2 = Main("weixie", "wuxiaoshen@shu.edu.cn", 32)
print(main1)
print(main2)
main1 += main2
print(main1)
print(main1*2)

#xiewei::->>>xie_wei_sh@foxmail.com::->>>24
#weixie::->>>wuxiaoshen@shu.edu.cn::->>>32
#xieweiweixie::->>>xie_wei_sh@foxmail.comwuxiaoshen@shu.edu.cn::->>>56
#112::->>>xie_wei_sh@foxmail.comwuxiaoshen@shu.edu.cnxie_wei_sh@foxmail.comwuxiaoshen@shu.edu.cn::->>>xieweiweixiexieweiweixie

6.

类, 实例及其他对象的内建函数

  1. hasattr()
  2. getattr()
  3. setattr()
  4. delattr()
  5. vars()
  6. 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", "xie_wei_sh@foxmail.com")
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", "xie_wei_sh@foxmail.com_copy")    # 设置属性值
print(vars(magicmethod))
delattr(magicmethod, "name")    # 删除属性name及其值
print(vars(magicmethod))

参考:[python cookbook]

帖子评论

关注 / 粉丝

我无话可说