最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python類的基本寫法與注釋風格介紹

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

Python類基本寫法與注釋風格

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

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

1.python中的類 Class

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

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中所有類的基類,在類的初始化時顯式繼承 

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

一個完整的類的聲明還會包括基本屬性、私有屬性和保護變量等內(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)進行初始化
		"""This is initial funciton"""
		self.name = name
		self.age = age
		#還可以定義各種其他的屬性,作為實例初始化時候?qū)鬟M來的參數(shù)進行賦值
		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是可以進行繼承以及方法重寫的,可以基于一個類繼承,也可以基于多個類進行多重繼承。

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ù),實現(xiàn)自己的特殊的方法"
		print('AoAoAoWu~~~~~~')

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

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

# 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....     #隨后詳細的說明類的細節(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."""
        # 下面是詳細的例子
		"""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ù)描述
	    
	    # 空一行,對齊詳細描述
	    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

最后完整的按照風格來寫一個類的示例:

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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python?魔法方法之?__?slots?__的實現(xiàn)

    python?魔法方法之?__?slots?__的實現(xiàn)

    本文主要介紹了python?魔法方法之?__?slots?__的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-03-03
  • 對django 2.x版本中models.ForeignKey()外鍵說明介紹

    對django 2.x版本中models.ForeignKey()外鍵說明介紹

    這篇文章主要介紹了對django 2.x版本中models.ForeignKey()外鍵說明介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • 純Python實現(xiàn)遺傳算法詳解

    純Python實現(xiàn)遺傳算法詳解

    遺傳算法(GA)是七十年代被霍蘭德提出來的,那還是8086的時代,但在如今的3nm時代,仍然散發(fā)著經(jīng)典的光輝,下面我們就來看看如何利用Python實現(xiàn)遺傳算法吧
    2023-08-08
  • python從入門到精通(DAY 2)

    python從入門到精通(DAY 2)

    本文是python從入門到精通系列文章的第二篇,主要給大家簡單講解下Python的字典復制和內(nèi)置函數(shù),非常簡單實用,需要的小伙伴可以參考下
    2015-12-12
  • 如何使用pycharm連接Databricks的步驟詳解

    如何使用pycharm連接Databricks的步驟詳解

    這篇文章主要介紹了如何使用pycharm連接Databricks,本文分步驟給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-09-09
  • Python從入門到精通之Hash函數(shù)的使用詳解

    Python從入門到精通之Hash函數(shù)的使用詳解

    Python提供了強大而靈活的Hash函數(shù),用于在各種應(yīng)用中實現(xiàn)數(shù)據(jù)存儲、數(shù)據(jù)校驗、加密等功能,下面將從入門到精通介紹Python中Hash函數(shù)的使用,感興趣的可以了解一下
    2023-08-08
  • Pytorch使用transforms

    Pytorch使用transforms

    這篇文章主要介紹了Pytorch使用transforms,tansforms功能,通俗地講,類似于在計算機視覺流程里的圖像預處理部分的數(shù)據(jù)增強。下面來看看文章的具體內(nèi)容介紹吧,需要的朋友可以參考一下
    2021-12-12
  • pytorch實現(xiàn)從本地加載 .pth 格式模型

    pytorch實現(xiàn)從本地加載 .pth 格式模型

    今天小編就為大家分享一篇pytorch實現(xiàn)從本地加載 .pth 格式模型,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • Ubuntu18.04安裝 PyCharm并使用 Anaconda 管理的Python環(huán)境

    Ubuntu18.04安裝 PyCharm并使用 Anaconda 管理的Python環(huán)境

    這篇文章主要介紹了Ubuntu18.04安裝 PyCharm并使用 Anaconda 管理的Python環(huán)境的教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-04-04
  • Python調(diào)用JavaScript代碼的方法

    Python調(diào)用JavaScript代碼的方法

    這篇文章主要介紹了Python調(diào)用JavaScript代碼的方法,幫助大家在不同場景里,采用的最佳調(diào)用方式,提高程序的性能,感興趣的朋友可以了解下
    2020-10-10

最新評論

博罗县| 内丘县| 华亭县| 四会市| 晴隆县| 秦皇岛市| 苍山县| 宁城县| 鸡东县| 虹口区| 三门县| 莱阳市| 会昌县| 临江市| 哈巴河县| 榆林市| 广州市| 大邑县| 连城县| 喀喇沁旗| 连南| 文安县| 临桂县| 嵩明县| 招远市| 湟中县| 上栗县| 临泽县| 成武县| 闽清县| 雷波县| 呼伦贝尔市| 专栏| 牟定县| 肇源县| 崇州市| 通州区| 缙云县| 吉首市| 澎湖县| 绥中县|