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

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),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-03-03
對django 2.x版本中models.ForeignKey()外鍵說明介紹
這篇文章主要介紹了對django 2.x版本中models.ForeignKey()外鍵說明介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
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)境的教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04

