Python类的基本写法与注释风格介绍

目录
  • Python类基本写法与注释风格
    • 1.python中的类 Class
    • 2.语言风格规范
    • Example
  • Python类的简单写法

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Python类和方法注释规范说明

    目录 Python类和方法注释规范 注释风格 小技巧 代码规范(含代码注释) 代码缩进和冒号 空行分隔代码段 包.模块的命名规范 类和对象的命名规范 函数的命名规范 代码注释 Python类和方法注释规范 注释风格 reStructuredText(PyCharm默认) def func(path, field_storage, temporary): '''基本描述 详细描述 :param path: The path of the file to wrap :type path: str :

  • Python+Matplotlib实现给图像添加文本标签与注释

    目录 1.添加文本标签 plt.text() 2. 添加注释 plt.annotate() 1.添加文本标签 plt.text() 用于在绘图过程中,在图像上指定坐标的位置添加文本.需要用到的是plt.text()方法.  其主要的参数有三个: plt.text(x, y, s) 其中x,y表示传入点的x和y轴坐标.s表示字符串. 需要注意的是,这里的坐标,如果设定有xticks.yticks标签,则指的不是标签,而是绘图时x.轴的原始值. 因为参数过多,不再一一解释,根据代码学习其用法. ha

  • Python中的多行注释文档编写风格汇总

    什么是docstring 在软件工程中,其实编码所占的部分是非常小的,大多是其它的事情,比如写文档.文档是沟通的工具. 在Python中,比较推崇在代码中写文档,代码即文档,比较方便,容易维护,直观,一致. 代码写完,文档也出来了.其实Markdown也差不多这种思想,文本写完,排版也完成了. 看看PEP 0257中对docstring的定义: A docstring is a string literal that occurs as the first statement in a modu

  • python中的三种注释方法

    目录 python注释方法 方式1 方式2 方式3 python小技巧 开头注释 设置路径 python注释方法 方式1 单行注释:shift + #(在代码的最前面输入,非选中代码进行注释) 多行注释:同单行一样在每一行的前面输入shift + #(较麻烦了) 方式2 单行和多行一样的方式:Ctr+ /  (前提是选中需要注释的代码) 方式3 输入''' '''或者""" """,将要注释的代码插在中间 ''' 这是多行注释,使用单引号. 这是

  • Python脚本,标识符,变量使用,脚本语句,注释,模块引用详解

    目录 一.python中的标志符: 二.Python中变量使用: 1.字符串变量 2.浮点数变量 3.整数变量和bool变量 三.Python中的语句 四.Python中的注释 五.Python中的模块: 1.inport <模块名> 2.from <模块名> import <代码元素> 3.from <模块名> import <代码元素> as <代码元素别名> 总结 一.python中的标志符: 1.给变量取的名字就是标志符 2.

  • Python类的基本写法与注释风格介绍

    目录 Python类基本写法与注释风格 1.python中的类 Class 2.语言风格规范 Example Python类的简单写法 Python类基本写法与注释风格 python是一种面向对象的语言,利用类的抽象可以大大提高代码的复用和结构,减少重复造轮子的过程,也让代码变得更加清晰易懂.便于维护. 1.python中的类 Class python中的类提供了一系列数据和方法的组合,类是python的一种对象,可以由它构建出新的实例.实例包含了类所具有的属性和类中声明的方法.首先来看一个基本

  • 一篇文章带你搞懂Python类的相关知识

    一.什么是类 类(class),作为代码的父亲,可以说它包裹了很多有趣的函数和方法以及变量,下面我们试着简单创建一个吧. 这样就算创建了我们的第一个类了.大家可以看到这里面有一个self,其实它指的就是类aa的实例.每个类中的函数只要你不是类函数或者静态函数你都得加上这个self,当然你也可以用其他的代替这个self,只不过这是python中的写法,就好比Java 中的this. 二.类的方法 1.静态方法,类方法,普通方法 类一般常用有三种方法,即为static method(静态方法),cl

  • Python类的高级函数详解

    __str__函数 如果定义了该函数,当print当前实例化对象的时候,会返回该函数的return信息 可用于定义当前类的描述信息 用法: def __str__(self): return str_type 参数:无 返回值:一般返回对于该类的描述信息 __getattr__函数 当调用的属性或者方法不存在时,会返回该方法定义的信息 用法: def __getattr__(self, key): print(something.-.) 参数: key: 调用任意不存在的属性名 返回值: 可以是

  • python类继承用法实例分析

    本文实例讲述了python类继承用法.分享给大家供大家参考.具体方法如下: #!/usr/bin/python # Filename: inherit.py class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name = name self.age = age print'(Initialized SchoolMember: %s)'% self.name def

  • Python 类与元类的深度挖掘 I【经验】

    上一篇介绍了 Python 枚举类型的标准库,除了考虑到其实用性,还有一个重要的原因是其实现过程是一个非常好的学习.理解 Python 类与元类的例子.因此接下来两篇就以此为例,深入挖掘 Python 中类与元类背后的机制. 翻开任何一本 Python 教程,你一定可以在某个位置看到下面这两句话: Python 中一切皆为对象(Everything in Python is an object); Python 是一种面向对象编程(Object Oriented Programming, OOP

  • 浅谈Python脚本开头及导包注释自动添加方法

    1.开头:#!/usr/bin/python和# -*- coding: utf-8 -*-的作用 – 指定 #!/usr/bin/python 是用来说明脚本语言是python的 是要用/usr/bin下面的程序(工具)python,这个解释器,来解释python脚本,来运行python脚本的. #!/usr/bin/python:是告诉操作系统执行这个脚本的时候,调用 /usr/bin 下的 python 解释器: #!/usr/bin/env python(推荐):这种用法是为了防止操作系

  • VSCode 添加自定义注释的方法(附带红色警戒经典注释风格)

    如何设置一个自定义注释 整洁的代码和注释风格总是给人一种眼前一亮.赏心悦目的感觉,同时详细的注释也是程序员所必须的职业素养之一 今天主要分享一下如何在VS Code中设置自定义 注释 第一步: 使用ctrl + shift + p 调出如下窗口,并且输入snippets 第二步:进入json文件编辑 这里以自定义js注释为例: 进入到 json 文件中后,添加如下代码,大家可以自定义设计,保存退出 我这里是一个类注释 一个方法注释 "Print to js class": { &quo

  • python类的继承实例详解

    python 类的继承 对于许多文章讲解python类的继承,大多数都是说一些什么oop,多态等概念,我认为这样可能对有一定基础的开发者帮助不是那么大,不如直接用在各种情况下所写的代码,来展示对于某一种代码情况,代码运行会有什么效果.这样可能对开发者的帮助更大.不说废话,直接上代码. 这里不区分经典类和新式类,下面分析的对新式类和经典类都适用 对于类中的__init__函数,只是一个初始化是调用的一个函数(ps:初始化和创建实例并不是一个过程,实例的创建是通过一个create函数来完成的),如果

  • python类中super()和__init__()的区别

    单继承时super()和__init__()实现的功能是类似的 class Base(object): def __init__(self): print 'Base create' class childA(Base): def __init__(self): print 'creat A ', Base.__init__(self) class childB(Base): def __init__(self): print 'creat B ', super(childB, self).__

随机推荐