1, classes and objects
#create a classclass fruit:def say (self):p rint "Hello, python" if __name__ = = "__main__": F = fruit () #不同于Java without Newf.say ()
2, properties and methods
#create a Classclass fruit:price = 0<span style= "white-space:pre" ></span> #类属性def __init__ (self): Self.color = "Red" zone = "China" #def getColor (self):p rint self.color@ Staticmethod#covert Ordinary method to static method def getprice ():p rint fruit.pricedef Say (self):p rint "Hello, python" if __name__ = = "__main__": F = fruit () F.say () Apple = Fru It () Apple.getcolor ()
Constructor, __init__ () method, optional, does not provide a default
destructor term frees the resource occupied by the object, __del__ ()
Garbage collection mechanism, Python uses a reference counting method.
Gc.collect () #显式调用垃圾回收器
3, inheritance
Class Fruit:def __init__ (self, color): Self.color = colorprint "Fruit ' color was%s"% Self.colordef sayname (self):p rint "F Ruit name "Class Apple (Fruit):d ef __init (self, color): fruit.__init__ (self, color) print" Apple's color is%s "% Self.colord EF sayname (self):p rint ' My name is Apple ' class Banana (Fruit):d ef __init__ (self, color): fruit.__init__ (self, color) print "Banana's color is%s"% self.colordef sayname (self):p rint "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):d ef __init (self): fruit.__init__ (self) print "apple" def sayname (self):p rint "My name is Apple "
# polymorphic, multiple inheritance slightly
Object-oriented Python notes