子类不想原封不动的继承父类的方法,而是做一些修改,这就是类的重写
-
#!/usr/bin/env python
-
# -*- coding:utf-8 -*-
-
# Author :Alvin.Xie
-
# @Time :2017/11/7 22:13
-
# @File :class3.py
-
-
-
# 类定义
-
class People(object):
-
name = 'ken'
-
age = 39
-
sex = 'F'
-
-
def __init__(self, n, a):
-
self.name = n
-
self.age = a
-
-
def speak(self):
-
print ("%s is speaking: I am %d years old" % (self.name, self.age))
-
-
-
p = People('tom', 10)
-
p.speak()
-
-
-
class Speaker(object):
-
topic = ''
-
name = 'bob'
-
-
def __init__(self, n, t):
-
self.name = n
-
self.topic = t
-
-
def speak(self):
-
print ("I am %s,I am a speaker!My topic is %s" % (self.name, self.topic))
-
-
-
test = Speaker('Tim', 'Python')
-
test.speak()
-
-
-
#类的继承
-
class Sample(People, Speaker):
-
a = ''
-
-
def __init__(self):
-
print 'my name is {0}'.format(self.name)
-
-
def get_name(self):
-
return self.name
-
-
def get_age(self):
-
return self.age
-
# 类的重写,只需要重新定义
-
-
def get_sex(self):
-
print "sex is man"
-
-
-
a = Sample()
-
print a.get_name()
-
print a.get_age()
-
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
私有变量/方法
私有变量/方法在自身类中不能直接调用,但是可以制作端口,控制变量引用.
-
#!/usr/bin/env python
-
# -*- coding:utf-8 -*-
-
# Author :Alvin.Xie
-
# @Time :2017/11/7 22:48
-
# @File :class4.py
-
-
-
class testPrivate:
-
def __init__(self):
-
self.__data = []
-
-
def add(self, item):
-
self.__data.append(item)
-
-
def printData(self):
-
print (self.__data)
-
-
-
t = testPrivate()
-
t.add('tom')
-
t.add('hello')
-
# t.printData()
-
print(t._testPrivate__data)
['tom', 'hello']
通过这样,我们在外面也能够访问该“私有”变量了,这一点在调试中是比较有用的!
阅读(1177) | 评论(0) | 转发(0) |