zoukankan      html  css  js  c++  java
  • Python笔记之面向对象

    1。类和对象

    #create a class
    class fruit:
    	def say(self):
    		print "hello, python"
    
    if __name__ == "__main__":
    	f = fruit()	#不同于Java,不用new
    	f.say()

    2,属性和方法

    #create a class
    class fruit:
    	price = 0<span style="white-space:pre">	</span>#类属性
    	def __init__(self):
    		self.color = "red"
    		zone = "china"	#
    	
    	def getColor(self):
    		print self.color
    	
    	@ staticmethod	#covert ordinary method to static method
    	def getPrice():
    		print fruit.price
    	
    	def say(self):
    		print "hello, python"
    
    if __name__ == "__main__":
    	f = fruit()
    	f.say()
    	apple = fruit()
    	apple.getColor()

    构造函数。__init__()方法,可选,不提供有默认的

    析构函数用语释放对象占用的资源。__del__()


    垃圾回收机制,Python採用引用计数方式。

    gc.collect() #显式调用垃圾回收器


    3。继承

    class Fruit:
    	def __init__(self, color):
    		self.color = color
    		print "fruit's color is %s" % self.color
    	
    	def sayname(self):
    		print "Fruit name"
    
    class Apple(Fruit):
    	def __init(self, color):
    		Fruit.__init__(self, color)
    		print "Apple's color is %s" % self.color
    	def 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.color
    	def sayname(self):
    		print "My name is banana"
    
    if __name__ == "__main__":
    	apple = Apple("red")
    	apple.sayname()
    
    	banana = Banana("yelloe")
    	banana.sayname()


    #抽象类模拟

    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"

    #多态。多重继承 略

  • 相关阅读:
    linux cut的用法
    删除表的语句(drop truncate delete)
    mysql中的模糊查询
    linux之软连接 硬链接 link ln
    使用robot合并Robot Framework测试报告
    Python中的字典
    python logger 动态设置日志名
    K8S(Kubernetes)学习笔记
    [转]CURL常用命令
    python网站目录扫描器2.0版
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5203406.html
Copyright © 2011-2022 走看看