首頁 > 軟體

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

2022-06-10 14:01:30

Python類基本寫法與註釋風格

python是一種物件導向的語言,利用類的抽象可以大大提高程式碼的複用和結構,減少重複造輪子的過程,也讓程式碼變得更加清晰易懂、便於維護。

1.python中的類 Class

python中的類提供了一系列資料和方法的組合,類是python的一種物件,可以由它構建出新的範例。範例包含了類所具有的屬性和類中宣告的方法。首先來看一個基本類的寫法:

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')

這是一個非常簡單的類,但其中包含了類很重要的幾個部分,包括類的宣告、初始化的建構函式、屬性、成員方法的定義等。

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

self是類裡的範例,為範例本身,在初始化後具有一系列的屬性和方法,類方法的第一個引數按照約定需要使用self開頭。

一個完整的類的宣告還會包括基本屬性、私有屬性和保護變數等內容:

class Dog(object):
	"""This is a dog class as example"""
	
	animal_kind = 'dog'    #基本屬性
	animal_legs = 4        #基本屬性也建議寫到初始化建構函式中去
	
	def __init__(self,name,age,params...):    #利用__init__(self,params)進行初始化
		"""This is initial funciton"""
		self.name = name
		self.age = age
		#還可以定義各種其他的屬性,作為範例初始化時候將傳進來的引數進行賦值
		self.__gender = 'male'        #兩個下劃線開頭是私有內部屬性,只能在類記憶體取
	
	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):
		"""重寫覆蓋父類別的函數,實現自己的特殊的方法"
		print('AoAoAoWu~~~~~~')

2.語言風格規範

為了更好的便於閱讀和複用程式碼,還需要使得程式碼滿足一定的語言風格,這裡選用了google的風格規範來對類進行宣告,下面是一個例子

# ref from:https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/
class MyDog(object):
    """Summary of class here.        #1.首先一句話簡短的總結這個類的功能和作,檔案字串需要用三引號包括
	
	# 對齊,空一行
	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....     #隨後詳細的說明類的細節
    Longer class information....     #類內部第一行的開始的文字都可以被__doc__
	
	# 空一行,開始寫這個類的各個屬性,包括資料型別和作用
    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.   #屬性的宣告,包括資料型別和作用,xxx型別的資料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.
		
		# 初始化的引數輸入,對於方法來說引數名(資料型別):描述的格式來寫
        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
	    # 輸入引數的初始化
        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.   #第一行簡寫函數描述
	    
	    # 空一行,對齊詳細描述
	    Extended description of function.
		
		# 空一行對齊,寫args 的各個內容,變數名(型別):描述
	    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,寫在前面用#做註釋,不屬於輸入的引數的初始化
		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 可從任意深度跳出函數,None

Python類的簡單寫法

class MyClass:
  name = ''
  age = 0
  __weight = 0 #私有變數
  
  def __init__(self, n, a, w): #self必須作為函數的第一個引數
    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()

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com