rapid gui programming with python and qt
DESCRIPTION
Rapid GUI Programming with Python and Qt. Classes and Modules By Raed S. Rasheed. Classes and Modules. Python fully supports procedural and object-oriented programming The syntax for creating a class is simple: class className ( base_classes ): suite. Creating Instances. - PowerPoint PPT PresentationTRANSCRIPT
1
Rapid GUI Programmingwith Python and Qt
Classes and ModulesBy
Raed S. Rasheed
2
Classes and Modules
Python fully supports procedural and object-oriented programming
The syntax for creating a class is simple:
class className(base_classes):suite
3
Creating Instances
Python has the __new__() special method which is called to construct an object, the __init__() special method which is called to initialize a newly constructed object.When an object is about to be garbage-collected its __del__() special method is called, with self as its only argument.We will create one that stores a string (the name of a kind of chair) and a number (how many legs the chair has):
class Chair(object):"""This class represents chairs."""
def __init__(self, name, legs=4): self.name = name self.legs = legs
4
Creating Instances
To create an instance of a class, we use the following syntax:instance = className(arguments)
for example:chair1 = Chair("Barcelona")chair2 = Chair("Bar Stool", 1)
Since the attributes are public, they can be read or assigned to using the dot (.) operator; for example:print chair2.name will print “Bar Stool”, and chair1.legs = 2 will change chair1’s legs attribute’s value from 4 to 2.
5
Methods and Special Methodsclass Rectangle(object):
def __init__(self, width, height):self.width = widthself.height = height
def getWidth(self):return self.width
def setWidth(self, width):self.width = width
def getHeight(self):return self.height
def setHeight(self, height):self.height = height
def area(self):return self.getWidth() * self.getHeight()
6
Methods and Special Methods
rect = Rectangle(50, 10)print rect.area() # Prints "500"rect.setWidth(20)
7
Methods and Special Methods
property() function
class Rectangle(object):def __init__(self, width, height):
self.width = widthself.height = height
def _area(self):return self.width * self.height
area = property(fget=_area)
8
Methods and Special Methods
rect = Rectangle(5, 4)print rect.width, rect.height, rect.area # Prints (5, 4, 20)rect.width = 6
9
Methods and Special Methods
def _width(self):return self.__width
def _setWidth(self, width):# Perform some computationself.__width = width
width = property(fget=_width, fset=_setWidth)
10
Methods and Special Methods
class Rectangle(object):def __init__(self, width, height):
self.__width = widthself.__height = height
def _area(self):return self.__width * self.__height
area = property(fget=_area)def _height(self):
return self.__heightdef _setHeight(self, height):
self.__height = heightheight = property(fget=_height, fset=_setHeight)
11
Methods and Special Methods
def _width(self): return self.__width
def _setWidth(self, width): self.__width = width
width = property(fget=_width, fset=_setWidth) def __cmp__(self, other):
return cmp(self.area, other.area)def __nonzero__(self):
return self.__width or self.__heightdef __repr__(self):
return "Rectangle(%d, %d)" % (self.__width, self.__height)
12
Methods and Special Methods
print ("Starting..\n")rect1 = Rectangle(4,5)print ("Area is [",rect1.area,"]")print ("Set width to [ 7 ] and height to [ 2 ]")rect1.width = 7rect1.height = 2print ("Now area is [",rect1.area,"]")print ("\nFinishing..")
13
Methods and Special Methods
Output:-
Starting..
Area is [ 20 ]Set width to [ 7 ] and height to [ 2 ]Now area is [ 14 ]
Finishing..
14
Methods and Special MethodsMethod Syntax Description__init__(self, args) x = X() Initializes a newly created instance__call__(self, args) x() Makes instances callable, that is,turnsthem into functors. The args are optional.__cmp__(self, other) x == yx < y# etc Returns -1 if self < other, 0 if they are equal, and 1 otherwise. If __cmp__() isimplemented, it will be used for any comparison operators that are not explicitly implemented.__eq__(self, other) x == y Returns True if x is equal to y__ne__(self, other) x != y Returns True if x is not equal to y__le__(self, other) x <= y Returns True if x is less than or equal to y
15
Methods and Special Methods
Method Syntax Description__lt__(self, other) x < y Returns True if x is less than y__ge__(self, other) x >= y Returns True if x is greater than orequal to y__gt__(self, other) x > y Returns True if x is greater than y__nonzero__(self) if x: passReturns True if x is nonzero__repr__(self) y = eval(`x`) Returns an eval()-able representation of x.Using backticks is the same as calling repr().__str__(self) print x Returns a human-readable representation of x__unicode__(self) print x Returns a human-readable Unicoderepresentation of x
16
Methods and Special Methods
def __cmp__(self, other):return cmp(self.area(), other.area())
rectA = Rectangle(4, 4)rectB = Rectangle(8, 2)rectA == rectB # True because both have the same arearectA < rectB # False
def __cmp__(self, other):if (self.width != other.width):
return cmp(self.width, other.width)return cmp(self.height, other.height)
17
Methods and Special Methods
def __nonzero__(self):return self.width or self.height)
def __repr__(self):return "Rectangle(%d, %d)" % (self.width, self.height)
18
Methods and Special Methods
Method Syntax Method Syntax__float__(self)float(x) __int__(self) int(x)__abs__(self) abs(x) __neg__(self) -x__add__(self, other) x + y __sub__(self, other) x - y__iadd__(self, other) x +=y __isub__(self, other) x -= y__radd__(self, other) y + x __rsub__(self, other) y - x__mul__(self, other) x * y __mod__(self, other) x % y__imul__(self, other) x *= y __imod__(self, other) x %= y__rmul__(self, other) y * x __rmod__(self, other) y % x__floordiv__(self, other) x // y __truediv__(self, other) x / y__ifloordiv__(self, other) x //= y __itruediv__(self, other) x /= y__rfloordiv__(self, other) y // x __rtruediv__(self, other) y / x
19
Static Data, and Static Methods and Decorators
class Balloon(object):unique_colors = set()def __init__(self, color):
self.color = colorBalloon.unique_colors.add(color)
@staticmethoddef uniqueColorCount():
return len(Balloon.unique_colors)@staticmethoddef uniqueColors():
return Balloon.unique_colors.copy()
20
Static Data, and Static Methods and Decorators
class Example: staticVariable = 5 print("starting\n")# Access through classprint (Example.staticVariable) # prints 5# Access through instanceinstance = Example()print (instance.staticVariable) # still 5
21
Static Data, and Static Methods and Decorators
# Change within instanceinstance.staticVariable = 6print (instance.staticVariable) # 6print (Example.staticVariable) # 5# Change through classExample.staticVariable = 7print (instance.staticVariable) # still 6print (Example.staticVariable) # now 7print("\nfinishing")
22
Static Data, and Static Methods and Decorators
class Example(object): name = "Example" @staticmethod def static(): print ("%s static() called" % Example.name) class Offspring1(Example): name = "Offspring1"
23
Static Data, and Static Methods and Decorators
class Offspring2(Example): name = "Offspring2" @staticmethod def static(): print ("%s static() called" % Offspring2.name)print("starting\n")Example.static() # prints ExampleOffspring1.static() # prints ExampleOffspring2.static() # prints Offspring2print("\nfinishing“)
24
Static Data, and Static Methods and Decorators
class Example: name = "Example" @classmethod def static(cls): print ("%s static() called" % cls.name)class Offspring1(Example): name = "Offspring1" pass
25
Static Data, and Static Methods and Decorators
class Offspring2(Example): name = "Offspring2" @classmethod def static(cls): print ("%s static() called" % cls.name)print("starting\n")Example.static() # prints ExampleOffspring1.static() # prints Offspring1Offspring2.static() # prints Offspring2print("\nfinishing")
26
Inheritance and Polymorphism
class Item(object): def __init__(self, artist, title, year=None): self.__artist = artist self.__title = title self.__year = year def artist(self): return self.__artist def setArtist(self, artist): self.__artist = artist
27
Inheritance and Polymorphism def title(self): return self.__title def setTitle(self, title): self.__title = title def year(self): return self.__year def setYear(self, year): self.__year = year def __str__(self): year = "" if self.__year is not None: year = " in %d" % self.__year return "%s by %s%s" % (self.__title, self.__artist, year)
28
Inheritance and Polymorphism
class Painting(Item): def __init__(self, artist, title, year=None): super(Painting, self).__init__(artist, title, year) # Item.__init__(self, artist, title, year)
class Sculpture(Item): def __init__(self, artist, title, year=None, material=None): super(Sculpture, self).__init__(artist, title, year) self.__material = material
29
Inheritance and Polymorphism
def material(self): return self.__material def setMaterial(self, material): self.__material = material def __str__(self): materialString = "" if self.__material is not None: materialString = " (%s)" % self.__material return "%s%s" % (super(Sculpture, self).__str__(), materialString)
30
Inheritance and Polymorphism
a = Painting("Cecil Collins", "The Sleeping Fool", 1943)
print a # Prints "The Sleeping Fool by Cecil Collins in 1943"
b = Sculpture("Auguste Rodin", "The Secret", 1925, "bronze")
print b # Prints "The Secret by Auguste Rodin in 1925 (bronze)"
31
Inheritance and Polymorphism
class Title(object):def __init__(self, title):
self.__title = title
def title(self):return self.__title
32
Inheritance and Polymorphism
items = []items.append(Painting("Cecil Collins", "The Poet", 1941))items.append(Sculpture("Auguste Rodin", "Naked Balzac", 1917,"plaster"))items.append(Title("Eternal Springtime"))
for item in items:print item.title()
The Poet by Cecil Collins in 1941Naked Balzac by Auguste Rodin in 1917 (plaster)Eternal Springtime
33
Inheritance and Polymorphism
class Item(object): def __init__(self, artist, title, year=None): self.__artist = artist self.__title = title
self.__year = yeardef title(self):
return self.__titledef setTitle(self, title):
self.__title = title
34
Inheritance and Polymorphism
items = []
for item in items:print item.title()
try:for item in items:
print item.title()except AttributeError:
pass
35
Inheritance and Polymorphism
for item in items:if isinstance(item, Item):print item.title()
for item in items:if hasattr(item, "title"):print item.title()
for item in items:if hasattr(item, "title") and callable(item.title):print item.title()
36
Modules and Multifile Applications
import Item
import mylibrary.Item
import mylibrary.Item as Item