Download presentation
Presentation is loading. Please wait.
Published byMilo Snow Modified over 8 years ago
1
Rapid GUI Programming with Python and Qt Classes and Modules By Raed S. Rasheed Classes and Modules By Raed S. Rasheed 1
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 Python fully supports procedural and object-oriented programming The syntax for creating a class is simple: class className(base_classes): suite 2
3
Creating Instances Python has the __new__() special method which is called to construct an object, 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. 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. 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 Python has the __new__() special method which is called to construct an object, 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. 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. 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 3
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. 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. 4
5
Methods and Special Methods class Rectangle(object): def __init__(self, width, height): self.width = width self.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() class Rectangle(object): def __init__(self, width, height): self.width = width self.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() 5
6
Methods and Special Methods rect = Rectangle(50, 10) print rect.area() # Prints "500" rect.setWidth(20) rect = Rectangle(50, 10) print rect.area() # Prints "500" rect.setWidth(20) 6
7
Methods and Special Methods property() function class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def _area(self): return self.width * self.height area = property(fget=_area) property() function class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def _area(self): return self.width * self.height area = property(fget=_area) 7
8
Methods and Special Methods rect = Rectangle(5, 4) print rect.width, rect.height, rect.area # Prints (5, 4, 20) rect.width = 6 rect = Rectangle(5, 4) print rect.width, rect.height, rect.area # Prints (5, 4, 20) rect.width = 6 8
9
Methods and Special Methods def _width(self): return self.__width def _setWidth(self, width): # Perform some computation self.__width = width width = property(fget=_width, fset=_setWidth) def _width(self): return self.__width def _setWidth(self, width): # Perform some computation self.__width = width width = property(fget=_width, fset=_setWidth) 9
10
Methods and Special Methods class Rectangle(object): def __init__(self, width, height): self.__width = width self.__height = height def _area(self): return self.__width * self.__height area = property(fget=_area) def _height(self): return self.__height def _setHeight(self, height): self.__height = height height = property(fget=_height, fset=_setHeight) height = property(fget=_height, fset=_setHeight) class Rectangle(object): def __init__(self, width, height): self.__width = width self.__height = height def _area(self): return self.__width * self.__height area = property(fget=_area) def _height(self): return self.__height def _setHeight(self, height): self.__height = height height = property(fget=_height, fset=_setHeight) height = property(fget=_height, fset=_setHeight) 10
11
Methods and Special Methods def _width(self): def _width(self): return self.__width return self.__width def _setWidth(self, width): def _setWidth(self, width): self.__width = 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.__height def __repr__(self): return "Rectangle(%d, %d)" % (self.__width, self.__height) def _width(self): def _width(self): return self.__width return self.__width def _setWidth(self, width): def _setWidth(self, width): self.__width = 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.__height def __repr__(self): return "Rectangle(%d, %d)" % (self.__width, self.__height) 11
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 = 7 rect1.height = 2 print ("Now area is [",rect1.area,"]") print ("\nFinishing..") print ("Starting..\n") rect1 = Rectangle(4,5) print ("Area is [",rect1.area,"]") print ("Set width to [ 7 ] and height to [ 2 ]") rect1.width = 7 rect1.height = 2 print ("Now area is [",rect1.area,"]") print ("\nFinishing..") 12
13
Methods and Special Methods Output:-Starting.. Area is [ 20 ] Set width to [ 7 ] and height to [ 2 ] Now area is [ 14 ] Finishing..Output:-Starting.. Area is [ 20 ] Set width to [ 7 ] and height to [ 2 ] Now area is [ 14 ] Finishing.. 13
14
Methods and Special Methods Method Syntax Description __init__(self, args) x = X() Initializes a newly created instance __call__(self, args) x() Makes instances callable, that is,turns them into functors. The args are optional. __cmp__(self, other)x == y x < y # etc Returns -1 if self < other, 0 if they are equal, and 1 otherwise. If __cmp__() is implemented, 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 Method Syntax Description __init__(self, args) x = X() Initializes a newly created instance __call__(self, args) x() Makes instances callable, that is,turns them into functors. The args are optional. __cmp__(self, other)x == y x < y # etc Returns -1 if self < other, 0 if they are equal, and 1 otherwise. If __cmp__() is implemented, 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 14
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 or equal 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 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 Unicode representation of x 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 or equal 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 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 Unicode representation of x 15
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 area rectA < rectB # False def __cmp__(self, other): if (self.width != other.width): return cmp(self.width, other.width) return cmp(self.height, other.height) 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 area rectA < rectB # False def __cmp__(self, other): if (self.width != other.width): return cmp(self.width, other.width) return cmp(self.height, other.height) 16
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) def __nonzero__(self): return self.width or self.height) def __repr__(self): return "Rectangle(%d, %d)" % (self.width, self.height) 17
18
Methods and Special Methods Method Syntax MethodSyntax __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 Method Syntax MethodSyntax __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 18
19
Static Data, and Static Methods and Decorators class Balloon(object): unique_colors = set() def __init__(self, color): self.color = color Balloon.unique_colors.add(color)@staticmethod def uniqueColorCount(): return len(Balloon.unique_colors) @staticmethod def uniqueColors(): return Balloon.unique_colors.copy() class Balloon(object): unique_colors = set() def __init__(self, color): self.color = color Balloon.unique_colors.add(color)@staticmethod def uniqueColorCount(): return len(Balloon.unique_colors) @staticmethod def uniqueColors(): return Balloon.unique_colors.copy() 19
20
Static Data, and Static Methods and Decorators class Example: staticVariable = 5 staticVariable = 5print("starting\n") # Access through class print (Example.staticVariable) # prints 5 # Access through instance instance = Example() print (instance.staticVariable) # still 5 class Example: staticVariable = 5 staticVariable = 5print("starting\n") # Access through class print (Example.staticVariable) # prints 5 # Access through instance instance = Example() print (instance.staticVariable) # still 5 20
21
Static Data, and Static Methods and Decorators # Change within instance instance.staticVariable = 6 print (instance.staticVariable) # 6 print (Example.staticVariable) # 5 # Change through class Example.staticVariable = 7 print (instance.staticVariable) # still 6 print (Example.staticVariable) # now 7 print("\nfinishing") # Change within instance instance.staticVariable = 6 print (instance.staticVariable) # 6 print (Example.staticVariable) # 5 # Change through class Example.staticVariable = 7 print (instance.staticVariable) # still 6 print (Example.staticVariable) # now 7 print("\nfinishing") 21
22
Static Data, and Static Methods and Decorators class Example(object): name = "Example" name = "Example" @staticmethod @staticmethod def static(): def static(): print ("%s static() called" % Example.name) print ("%s static() called" % Example.name) class Offspring1(Example): name = "Offspring1" name = "Offspring1" class Example(object): name = "Example" name = "Example" @staticmethod @staticmethod def static(): def static(): print ("%s static() called" % Example.name) print ("%s static() called" % Example.name) class Offspring1(Example): name = "Offspring1" name = "Offspring1" 22
23
Static Data, and Static Methods and Decorators class Offspring2(Example): name = "Offspring2" name = "Offspring2" @staticmethod @staticmethod def static(): def static(): print ("%s static() called" % Example.name) print ("%s static() called" % Example.name)print("starting\n") Example.static() # prints Example Offspring1.static() # prints Example Offspring2.static() # prints Offspring2 print("\nfinishing“) class Offspring2(Example): name = "Offspring2" name = "Offspring2" @staticmethod @staticmethod def static(): def static(): print ("%s static() called" % Example.name) print ("%s static() called" % Example.name)print("starting\n") Example.static() # prints Example Offspring1.static() # prints Example Offspring2.static() # prints Offspring2 print("\nfinishing“) 23
24
Static Data, and Static Methods and Decorators class Example: name = "Example" name = "Example" @classmethod @classmethod def static(cls): def static(cls): print ("%s static() called" % cls.name) print ("%s static() called" % cls.name) class Offspring1(Example): name = "Offspring1" name = "Offspring1" pass pass class Example: name = "Example" name = "Example" @classmethod @classmethod def static(cls): def static(cls): print ("%s static() called" % cls.name) print ("%s static() called" % cls.name) class Offspring1(Example): name = "Offspring1" name = "Offspring1" pass pass 24
25
Static Data, and Static Methods and Decorators class Offspring2(Example): name = "Offspring2" name = "Offspring2" @classmethod @classmethod def static(cls): def static(cls): print ("%s static() called" % cls.name) print ("%s static() called" % cls.name)print("starting\n") Example.static() # prints Example Offspring1.static() # prints Offspring1 Offspring2.static() # prints Offspring2 print("\nfinishing") class Offspring2(Example): name = "Offspring2" name = "Offspring2" @classmethod @classmethod def static(cls): def static(cls): print ("%s static() called" % cls.name) print ("%s static() called" % cls.name)print("starting\n") Example.static() # prints Example Offspring1.static() # prints Offspring1 Offspring2.static() # prints Offspring2 print("\nfinishing") 25
26
Inheritance and Polymorphism class Item(object): def __init__(self, artist, title, year=None): def __init__(self, artist, title, year=None): self.__artist = artist self.__artist = artist self.__title = title self.__title = title self.__year = year self.__year = year def artist(self): def artist(self): return self.__artist return self.__artist def setArtist(self, artist): def setArtist(self, artist): self.__artist = artist self.__artist = artist def title(self): def title(self): return self.__title return self.__title class Item(object): def __init__(self, artist, title, year=None): def __init__(self, artist, title, year=None): self.__artist = artist self.__artist = artist self.__title = title self.__title = title self.__year = year self.__year = year def artist(self): def artist(self): return self.__artist return self.__artist def setArtist(self, artist): def setArtist(self, artist): self.__artist = artist self.__artist = artist def title(self): def title(self): return self.__title return self.__title 26
27
Inheritance and Polymorphism def title(self): def title(self): return self.__title return self.__title def setTitle(self, title): def setTitle(self, title): self.__title = title self.__title = title def year(self): def year(self): return self.__year return self.__year def setYear(self, year): def setYear(self, year): self.__year = year self.__year = year def __str__(self): def __str__(self): year = "" year = "" if self.__year is not None: if self.__year is not None: year = " in %d" % self.__year year = " in %d" % self.__year return "%s by %s%s" % (self.__title, self.__artist, year) return "%s by %s%s" % (self.__title, self.__artist, year) def title(self): def title(self): return self.__title return self.__title def setTitle(self, title): def setTitle(self, title): self.__title = title self.__title = title def year(self): def year(self): return self.__year return self.__year def setYear(self, year): def setYear(self, year): self.__year = year self.__year = year def __str__(self): def __str__(self): year = "" year = "" if self.__year is not None: if self.__year is not None: year = " in %d" % self.__year year = " in %d" % self.__year return "%s by %s%s" % (self.__title, self.__artist, year) return "%s by %s%s" % (self.__title, self.__artist, year) 27
28
Inheritance and Polymorphism class Painting(Item): def __init__(self, artist, title, year=None): def __init__(self, artist, title, year=None): super(Painting, self).__init__(artist, title, year) super(Painting, self).__init__(artist, title, year) # item.__init__(self, artist, title, year) # item.__init__(self, artist, title, year) class Sculpture(Item): def __init__(self, artist, title, year=None, material=None): def __init__(self, artist, title, year=None, material=None): super(Sculpture, self).__init__(artist, title, year) super(Sculpture, self).__init__(artist, title, year) self.__material = material self.__material = material class Painting(Item): def __init__(self, artist, title, year=None): def __init__(self, artist, title, year=None): super(Painting, self).__init__(artist, title, year) super(Painting, self).__init__(artist, title, year) # item.__init__(self, artist, title, year) # item.__init__(self, artist, title, year) class Sculpture(Item): def __init__(self, artist, title, year=None, material=None): def __init__(self, artist, title, year=None, material=None): super(Sculpture, self).__init__(artist, title, year) super(Sculpture, self).__init__(artist, title, year) self.__material = material self.__material = material 28
29
Inheritance and Polymorphism def material(self): def material(self): return self.__material return self.__material def setMaterial(self, material): def setMaterial(self, material): self.__material = material self.__material = material def __str__(self): def __str__(self): materialString = "" materialString = "" if self.__material is not None: if self.__material is not None: materialString = " (%s)" % self.__material materialString = " (%s)" % self.__material return "%s%s" % (super(Sculpture, self).__str__(), materialString) return "%s%s" % (super(Sculpture, self).__str__(), materialString) def material(self): def material(self): return self.__material return self.__material def setMaterial(self, material): def setMaterial(self, material): self.__material = material self.__material = material def __str__(self): def __str__(self): materialString = "" materialString = "" if self.__material is not None: if self.__material is not None: materialString = " (%s)" % self.__material materialString = " (%s)" % self.__material return "%s%s" % (super(Sculpture, self).__str__(), materialString) return "%s%s" % (super(Sculpture, self).__str__(), materialString) 29
30
Inheritance and Polymorphism class Title(object): def __init__(self, title) self.__title = title def title(self): return self.__title return "%s%s" % (super(Sculpture, self).__str__(), materialString) return "%s%s" % (super(Sculpture, self).__str__(), materialString) class Title(object): def __init__(self, title) self.__title = title def title(self): return self.__title return "%s%s" % (super(Sculpture, self).__str__(), materialString) return "%s%s" % (super(Sculpture, self).__str__(), materialString) 30
31
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() 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() 31
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.