欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python類的基本寫法與注釋風(fēng)格介紹

 更新時(shí)間:2022年06月10日 11:33:17   作者:hitrjj  
這篇文章主要介紹了Python類的基本寫法與注釋風(fēng)格,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Python類基本寫法與注釋風(fēng)格

python是一種面向?qū)ο蟮恼Z言,利用類的抽象可以大大提高代碼的復(fù)用和結(jié)構(gòu),減少重復(fù)造輪子的過程,也讓代碼變得更加清晰易懂、便于維護(hù)。

https://runnable.com/docker/python/

1.python中的類 Class

python中的類提供了一系列數(shù)據(jù)和方法的組合,類是python的一種對象,可以由它構(gòu)建出新的實(shí)例。實(shí)例包含了類所具有的屬性和類中聲明的方法。首先來看一個基本類的寫法:

class Dog(object):
	"""This is a dog class as example"""
	def __init__(self,name):
		"""This is initial funciton"""
		self.name = name
	
	def voice(self):
		"""Dog will speak as wangwang """
		print('WangWangWang')

這是一個非常簡單的類,但其中包含了類很重要的幾個部分,包括類的聲明、初始化的構(gòu)造函數(shù)、屬性、成員方法的定義等。

其中有幾個地方需要注意:object是python中所有類的基類,在類的初始化時(shí)顯式繼承 

self是類里的實(shí)例,為實(shí)例本身,在初始化后具有一系列的屬性和方法,類方法的第一個參數(shù)按照約定需要使用self開頭。

一個完整的類的聲明還會包括基本屬性、私有屬性和保護(hù)變量等內(nèi)容:

class Dog(object):
	"""This is a dog class as example"""
	
	animal_kind = 'dog'    #基本屬性
	animal_legs = 4        #基本屬性也建議寫到初始化構(gòu)造函數(shù)中去
	
	def __init__(self,name,age,params...):    #利用__init__(self,params)進(jìn)行初始化
		"""This is initial funciton"""
		self.name = name
		self.age = age
		#還可以定義各種其他的屬性,作為實(shí)例初始化時(shí)候?qū)鬟M(jìn)來的參數(shù)進(jìn)行賦值
		self.__gender = 'male'        #兩個下劃線開頭是私有內(nèi)部屬性,只能在類內(nèi)訪問
	
	def __privateGender(self):
		"""This is pravate method"""
		print('This dog gender is %s',self.__gender)	
	def voice(self):
		"""Dog will speak as wangwang """
		print('WangWangWang')
		print(self.__privateGender(self))
	def run(self):
		"""runing with legs"""
		print("This dog has %d legs to run"%self.animal_legs)
	#定義一大堆各種各樣的方法

class是可以進(jìn)行繼承以及方法重寫的,可以基于一個類繼承,也可以基于多個類進(jìn)行多重繼承。

class Husky(Dog):
	"""Husky inherent the Dog attris and method"""
	def __init__(self,name,age,color,params):
		Dog.__init__(self, name, age)   #利用Dog這個父類的初始化
		self.color = color              #子類中特定屬性的初始化
	def jump(self):
		"""Husky special jump function"""
		print('This dog could jump jump')
	
	def voice(self):
		"""重寫覆蓋父類的函數(shù),實(shí)現(xiàn)自己的特殊的方法"
		print('AoAoAoWu~~~~~~')

2.語言風(fēng)格規(guī)范

為了更好的便于閱讀和復(fù)用代碼,還需要使得代碼滿足一定的語言風(fēng)格,這里選用了google的風(fēng)格規(guī)范來對類進(jìn)行聲明,下面是一個例子

# ref from:https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/
class MyDog(object):
    """Summary of class here.        #1.首先一句話簡短的總結(jié)這個類的功能和作,文檔字符串需要用三引號包括
	
	# 對齊,空一行
	If the class has public attributes, they may be documented here
    in an ``Attributes`` section and follow the same formatting as a
    function's ``Args`` section. Alternatively, attributes may be documented
    inline with the attribute's declaration (see __init__ method below).
    Properties created with the ``@property`` decorator should be documented
    in the property's getter method.
   
    Longer class information....     #隨后詳細(xì)的說明類的細(xì)節(jié)
    Longer class information....     #類內(nèi)部第一行的開始的文字都可以被__doc__
	
	# 空一行,開始寫這個類的各個屬性,包括數(shù)據(jù)類型和作用
    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.   #屬性的聲明,包括數(shù)據(jù)類型和作用,xxx類型的數(shù)據(jù)for/used to/ofxxx
        eggs: An integer count of the eggs we have laid.
    """
    def __init__(self, likes_spam=False):
        """Inits SampleClass with blah."""
        # 下面是詳細(xì)的例子
		"""Example of docstring on the __init__ method.
		
		# 對于初始化方法的說明
        The __init__ method may be documented in either the class level
        docstring, or as a docstring on the __init__ method itself.
        Either form is acceptable, but the two should not be mixed. Choose one
        convention to document the __init__ method and be consistent with it.
		
		# 對于初始化方法的一些記錄
        Note:
            Do not include the `self` parameter in the ``Args`` section.
		
		# 初始化的參數(shù)輸入,對于方法來說參數(shù)名(數(shù)據(jù)類型):描述的格式來寫
        Args:
            param1 (str): Description of `param1`.
            param2 (:obj:`int`, optional): Description of `param2`. Multiple
                lines are supported.
            param3 (:obj:`list` of :obj:`str`): Description of `param3`.
        """
        self.likes_spam = likes_spam
        self.eggs = 0
	    # 輸入?yún)?shù)的初始化
        self.attr1 = param1
        self.attr2 = param2
        self.attr3 = param3  #: Doc comment *inline* with attribute
        #: list of str: Doc comment *before* attribute, with type specified
        self.attr4 = ['attr4']
        self.attr5 = None
        """str: Docstring *after* attribute, with type specified."""
    def public_method(self):
        """Performs operation blah."""
        """Summary line.   #第一行簡寫函數(shù)描述
	    
	    # 空一行,對齊詳細(xì)描述
	    Extended description of function.
		
		# 空一行對齊,寫args 的各個內(nèi)容,變量名(類型):描述
	    Args:
	        arg1 (int): Description of arg1
	        arg2 (str): Description of arg2
		
		# 空一行對齊,不同情況下的if else 返回值(類型):描述
	    Returns:
	        int/float/bool dtype: Description of return value
	
	    """

Example

最后完整的按照風(fēng)格來寫一個類的示例:

class Dog(object):
	"""
	This is a class for Dog 
	Dog class is the parents class of all dog, this class contain 
	general attributes of dog and some common function of dogs, such as
	num legs, the voice fucntion, the runing functions.
	
	Attributes:
		name: 	A string of dog's name
		kind: 	A string of dog's family
		age:  	A integer of dog years
		gender: A boolean gender of dog, male=1 of famle=0
		legs    A integer if dog's legs
		weight: A float of dogs weight
		size:   A string of dogs, one of big, middle, smal
	"""
	
	def __init__(self,args,gender,size):
		"""initialize dog class, all attributes pass in with args, which is a dict or indepent params
		Input contain dict and str params, also there is private attribute
		
		Args:
			args.name(str): dog name
			args.kind(str): dog family
			args.age(int) : dog age
			gender(bool)  : dog gender, male=1,famale=0
		args.weight(float): dog weight
			size(str)     : dog size
		"""
		self.name = args.name
		self.kind = args.kind
		self.age = args.age
		self.weight = args.weight
		
		# __legs(int) : dog legs,privite attribute, not the inputs params,寫在前面用#做注釋,不屬于輸入的參數(shù)的初始化
		self.__legs = 4  
		"""寫在后面用三引號__legs(int)   : dog legs,privite attribute"""
		
		self.size = size
		self.gender = gender
		
	def voice(self,size):
		"""This is dog speak fucntion
	
		Different dog with different voice 
		which related to the size,age and kind
		Args:
			size(str): dog size
			age(int) : dog age
			kind(srt): dog kind
			
		Returns:
		    None, just print the voice
	    """
		if size=='big':
			print('Big WangWang')
		elif size =='middle':
			print('M wang')		
		elif size=='small':
			print('Miao')
		
		# 附注:return 可從任意深度跳出函數(shù),None

Python類的簡單寫法

class MyClass:
  name = ''
  age = 0
  __weight = 0 #私有變量
  
  def __init__(self, n, a, w): #self必須作為函數(shù)的第一個參數(shù)
    self.name = n
    self.age = a
    self.__weight = w
  def speak(self):
    print('%s 說:我 %s 歲'%(self.name, self.age))
x = MyClass('yao', 10, 30)
x.speak()

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python 搜索大文件的實(shí)例代碼

    python 搜索大文件的實(shí)例代碼

    今天小編就為大家分享一篇python 搜索大文件的實(shí)例代碼,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • python變量賦值機(jī)制踩坑記錄

    python變量賦值機(jī)制踩坑記錄

    這篇文章主要介紹了python變量賦值機(jī)制踩坑記錄,我們都知道python有深拷貝和淺拷貝,但變量賦值又是什么機(jī)制呢?這是個容易被忽略卻又極易踩坑的點(diǎn),下面我們來一探究竟,需要的朋友可以參考一下
    2022-02-02
  • python2 與 pyhton3的輸入語句寫法小結(jié)

    python2 與 pyhton3的輸入語句寫法小結(jié)

    這篇文章主要給大家介紹了關(guān)于python2 與 pyhton3的輸入語句寫法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-09-09
  • CentOS中安裝python3.8.2的詳細(xì)教程

    CentOS中安裝python3.8.2的詳細(xì)教程

    這篇文章主要介紹了CentOS中安裝python3.8.2的詳細(xì)教程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • 關(guān)于Flask 視圖介紹

    關(guān)于Flask 視圖介紹

    這篇文章主要分享的是關(guān)于Flask 視圖介紹, Flask 中路由是請求的 url 與處理函數(shù)之間的映射,使用app.route裝飾器將處理函數(shù)和 url 綁定,路由綁定的處理函數(shù)就被成為視圖函數(shù)。下面來看文章的詳細(xì)內(nèi)容,需要的朋友也可以參考一下
    2021-11-11
  • python 實(shí)現(xiàn)手機(jī)自動撥打電話的方法(通話壓力測試)

    python 實(shí)現(xiàn)手機(jī)自動撥打電話的方法(通話壓力測試)

    今天小編就為大家分享一篇python 實(shí)現(xiàn)手機(jī)自動撥打電話的方法(通話壓力測試),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Python爬取豆瓣視頻信息代碼實(shí)例

    Python爬取豆瓣視頻信息代碼實(shí)例

    這篇文章主要介紹了Python爬取豆瓣視頻信息代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • 以SortedList為例詳解Python的defaultdict對象使用自定義類型的方法

    以SortedList為例詳解Python的defaultdict對象使用自定義類型的方法

    這篇文章主要介紹了以SortedList為例詳解Python的defaultdict對象使用自定義類型的方法,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下
    2022-07-07
  • Python PyQt5干貨滿滿小項(xiàng)目輕松實(shí)現(xiàn)高效摳圖去背景

    Python PyQt5干貨滿滿小項(xiàng)目輕松實(shí)現(xiàn)高效摳圖去背景

    PyQt5以一套Python模塊的形式來實(shí)現(xiàn)功能。它包含了超過620個類,600個方法和函數(shù)。本篇文章手把手帶你用PyQt5輕松實(shí)現(xiàn)圖片扣除背景,大家可以在過程中查缺補(bǔ)漏,提升水平
    2021-11-11
  • Python3將數(shù)據(jù)保存為txt文件的方法

    Python3將數(shù)據(jù)保存為txt文件的方法

    這篇文章主要介紹了Python3將數(shù)據(jù)保存為txt文件的方法,非常不錯,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-09-09

最新評論