Chinaunix首页 | 论坛 | 博客
  • 博客访问: 231205
  • 博文数量: 57
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 557
  • 用 户 组: 普通用户
  • 注册时间: 2015-10-01 18:05
文章分类

全部博文(57)

文章存档

2017年(57)

我的朋友

分类: Python/Ruby

2017-11-07 23:04:21

子类不想原封不动的继承父类的方法,而是做一些修改,这就是类的重写

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author :Alvin.Xie
  4. # @Time :2017/11/7 22:13
  5. # @File :class3.py


  6. # 类定义
  7. class People(object):
  8.     name = 'ken'
  9.     age = 39
  10.     sex = 'F'

  11.     def __init__(self, n, a):
  12.         self.name = n
  13.         self.age = a

  14.     def speak(self):
  15.         print ("%s is speaking: I am %d years old" % (self.name, self.age))


  16. p = People('tom', 10)
  17. p.speak()


  18. class Speaker(object):
  19.     topic = ''
  20.     name = 'bob'

  21.     def __init__(self, n, t):
  22.         self.name = n
  23.         self.topic = t

  24.     def speak(self):
  25.         print ("I am %s,I am a speaker!My topic is %s" % (self.name, self.topic))


  26. test = Speaker('Tim', 'Python')
  27. test.speak()


  28. #类的继承
  29. class Sample(People, Speaker):
  30.     a = ''

  31.     def __init__(self):
  32.         print 'my name is {0}'.format(self.name)

  33.     def get_name(self):
  34.         return self.name

  35.     def get_age(self):
  36.         return self.age
  37.     # 类的重写,只需要重新定义

  38.     def get_sex(self):
  39.         print "sex is man"


  40. a = Sample()
  41. print a.get_name()
  42. print a.get_age()
  43. a.get_sex()
执行结果如下
tom is speaking: I am 10 years old
I am Tim,I am a speaker!My topic is Python
my name is ken
ken
39
sex is man

私有变量/方法
私有变量/方法在自身类中不能直接调用,但是可以制作端口,控制变量引用.

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author :Alvin.Xie
  4. # @Time :2017/11/7 22:48
  5. # @File :class4.py


  6. class testPrivate:
  7.     def __init__(self):
  8.         self.__data = []

  9.     def add(self, item):
  10.         self.__data.append(item)

  11.     def printData(self):
  12.         print (self.__data)


  13. t = testPrivate()
  14. t.add('tom')
  15. t.add('hello')
  16. # t.printData()
  17. print(t._testPrivate__data)
['tom', 'hello']

通过这样,我们在外面也能够访问该“私有”变量了,这一点在调试中是比较有用的!





阅读(1147) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~