Python notes object-oriented
1. Classes and objects
# Create a classclass fruit: def say (self): print "hello, python" if _ name _ = "_ main _": f = fruit () # unlike Java, newf is not required. say ()
2. attributes and Methods
# Create a classclass fruit: price = 0 # class attribute def _ init _ (self): self. color = "red" zone = "china" # def getColor (self): print self. color @ staticmethod # covert ordinary method to static methoddef getPrice (): print fruit. pricedef say (self): print "hello, python" if _ name _ = "_ main _": f = fruit () f. say () apple = fruit () apple. getColor ()
The __init _ () method of the constructor. Optional. The default value is not provided.
Destructor terms release resources occupied by objects, __del __()
The garbage collection mechanism. Python uses the reference counting method.
Gc. collect () # explicitly call the Garbage Collector
3. Inheritance
class Fruit:def __init__(self, color):self.color = colorprint "fruit's color is %s" % self.colordef sayname(self):print "Fruit name"class Apple(Fruit):def __init(self, color):Fruit.__init__(self, color)print "Apple's color is %s" % self.colordef sayname(self):print "My name is Apple"class Banana(Fruit):def __init__(self, color):Fruit.__init__(self, color)print "Banana's color is %s" % self.colordef sayname(self):print "My name is banana"if __name__ == "__main__":apple = Apple("red")apple.sayname()banana = Banana("yelloe")banana.sayname()
# Abstract class simulation
def abstract():raise NotImplementError(“abstract”)class Fruit:def __init__(self):if self.__class__ is Fruit:abstract()print “Fruit”class Apple(Fruit):def __init(self):Fruit.__init__(self)print "Apple"def sayname(self):print "My name is Apple"
# Polymorphism, multi-Inheritance