360 likes | 544 Views
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.
E N D
Rapid GUI Programmingwith 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 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
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.
Methods and Special Methods class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height defgetWidth(self): return self.width defsetWidth(self, width): self.width = width defgetHeight(self): return self.height defsetHeight(self, height): self.height = height def area(self): return self.getWidth() * self.getHeight()
Methods and Special Methods rect = Rectangle(50, 10) print rect.area() # Prints "500" rect.setWidth(20)
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)
Methods and Special Methods rect = Rectangle(5, 4) print rect.width, rect.height, rect.area # Prints (5, 4, 20) rect.width = 6
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)
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)
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.__height def __repr__(self): return "Rectangle(%d, %d)" % (self.__width, self.__height)
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..")
Methods and Special Methods Output:- Starting.. Area is [ 20 ] Set width to [ 7 ] and height to [ 2 ] Now area is [ 14 ] Finishing..
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
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: pass Returns 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
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)
Methods and Special Methods def __nonzero__(self): return self.width or self.height) def __repr__(self): return "Rectangle(%d, %d)" % (self.width, self.height)
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
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 defuniqueColorCount(): return len(Balloon.unique_colors) @staticmethod defuniqueColors(): return Balloon.unique_colors.copy()
Static Data, and Static Methods and Decorators class Example: staticVariable = 5 print("starting\n") # Access through class print (Example.staticVariable) # prints 5 # Access through instance instance = Example() print (instance.staticVariable) # still 5
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")
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"
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 Example Offspring1.static() # prints Example Offspring2.static() # prints Offspring2 print("\nfinishing“)
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
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 Example Offspring1.static() # prints Offspring1 Offspring2.static() # prints Offspring2 print("\nfinishing")
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 defsetArtist(self, artist): self.__artist = artist
Inheritance and Polymorphism def title(self): return self.__title defsetTitle(self, title): self.__title = title def year(self): return self.__year defsetYear(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)
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
Inheritance and Polymorphism def material(self): return self.__material defsetMaterial(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)
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)"
Inheritance and Polymorphism class Title(object): def__init__(self, title): self.__title = title deftitle(self): return self.__title
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 1941 Naked Balzac by Auguste Rodin in 1917 (plaster) Eternal Springtime
Inheritance and Polymorphism class Item(object): def__init__(self, artist, title, year=None): self.__artist = artist self.__title = title self.__year = year deftitle(self): return self.__title defsetTitle(self, title): self.__title = title
Inheritance and Polymorphism items = [] for item in items: print item.title() try: for item in items: print item.title() except AttributeError: pass
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()
Modules and Multifile Applications import Item import mylibrary.Item import mylibrary.Itemas Item