Python notes object-oriented

Source: Internet
Author: User

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

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.