Object-oriented Python notes

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.