[cairo] pycairo subclass

zs stryhal at sci.ujep.cz
Mon Dec 10 02:37:20 PST 2007


Hi,

OK .. I understand that it's not a good idea to subclass cairo surfaces, so it's forbidden.
But I found, one can easily overshoot this ban like that:

# ---------------- example begin ----------------
import cairo


class derived_context(object):
	def __init__(self,w,h,fn):
		self.s=cairo.PDFSurface(fn, w, h)
		self.c=cairo.Context(self.s)
	
	# ---- 	inherited methods -----	
	def move_to(self,x,y):
		self.c.move_to(x,y)
		
	def line_to(self,x,y):
		self.c.line_to(x,y)

	def rel_line_to(self,x,y):
		self.c.rel_line_to(x,y)
	
	def close_path(self):
		self.c.close_path()

	def stroke(self):
		self.c.stroke()
		
	# ---- 	new methods -----
	def triangle(self):
		self.rel_line_to(10,0)
		self.rel_line_to(-5,7)
		self.close_path()

if __name__== "__main__":
	d=derived_context(100,100,'pokus.pdf')
	d.move_to(50,50)
	d.triangle()
	d.stroke()

# ---------------- example end ----------------

Does this approach have the problem with memory leaks too?
I don't think so, but I'm new in python and I don't know much about wraping C library and realted problems.
It works ... but it's ugly. If this is the only way, it should be written(highlighted) on web page and documentation. The information about forbidden subclassing is inconceivably hidden.

> cairo.Context a special case which should allow subclassing?

I suppose, it might be useful.


> How useful would subclassing cairo.Context be?

It may be useful in cases, where somebody need to enrich the set of method by some special reusable painting procedures.
I know, one can do it through functions without subclassing, but once we use OOP programing language, why not to use all the advantages. For emaple, why should we write:

	d.move_to(50,50)
	triangle(d)

instead of:
	d.move_to(50,50)
	d.triangle()

Regards

Zdenek Stryhal

		


More information about the cairo mailing list