Basic Python class writing and commenting style
python is an object-oriented language, the use of class abstraction can greatly improve the reuse and structure of the code, reduce the repetition of the process of building wheels, but also make the code more clear and easy to understand, easy to maintain.
Classes in the Class
Classes in python provide a combination of data and methods; a class is an object in python from which new instances can be constructed. Instances contain the properties that the class has and the methods declared in the class. Let's first look at how a basic class is written:
class Dog(object): """This is a dog class as example""" def __init__(self,name): """This is initial funciton""" = name def voice(self): """Dog will speak as wangwang """ print('WangWangWang')
This is a very simple class, but it contains several very important parts of the class, including the declaration of the class, the constructor for initialization, the definition of properties, member methods, etc.
There are a couple of areas to keep in mind:objectis the base class for all classes in python, and is explicitly inherited at class initialization time
selfis an instance of the class, for the instance itself, after initialization has a series of properties and methods, the first parameter of the class method according to the convention need to use self to start.
The declaration of a complete class will also include things like basic attributes, private attributes, and protected variables:
class Dog(object): """This is a dog class as example""" animal_kind = 'dog' #Basic Properties animal_legs = 4 # Basic properties are also recommended to be written to the initialization constructor def __init__(self,name,age,params...): # Initialize using __init__(self,params) """This is initial funciton""" = name = age #Various other attributes can be defined to assign values to incoming parameters when the instance is initialized. self.__gender = 'male' # Two underscores at the beginning are private internal attributes that can only be accessed within a class 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) #Define a whole bunch of different methods
class is able to performpredecessorand methodologyrewrites, which can be inherited based on a single class or multiple inheritance based on multiple classes.
class Husky(Dog): """Husky inherent the Dog attris and method""" def __init__(self,name,age,color,params): Dog.__init__(self, name, age) # Utilize Dog as a parent class initialization = color # Initialization of specific attributes in subclasses def jump(self): """Husky special jump function""" print('This dog could jump jump') def voice(self): """Overwrite functions that override parent classes to implement their own special methods" print('AoAoAoWu~~~~~~')
2. Language style standardization
In order to better facilitate the reading and reuse of the code, you also need to make the code to meet a certain language style, here the choice of google's style specification to declare the class, the following is an example
# ref from:/en/latest/google-python-styleguide/python_style_rules/ class MyDog(object): """Summary of class here. #1. First of all, a short sentence summarizes the function of the class and the work, the document string needs to use three quotes include # Aligned, blank lines 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.... # Subsequent elaboration of class details Longer class information.... # The text at the beginning of the first line inside the class can be __doc__ by # A blank line to start writing the attributes of the class, including data types and roles. Attributes: likes_spam: A boolean indicating if we like SPAM or not. #Declaration of attributes, including data types and roles, xxx types of data for/used to/ofxxx eggs: An integer count of the eggs we have laid. """ def __init__(self, likes_spam=False): """Inits SampleClass with blah.""" # Here's a detailed example """Example of docstring on the __init__ method. # Description of the initialization 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. # Some notes on initialization methods Note: Do not include the `self` parameter in the ``Args`` section. # Parameter input for initialization, for methods Parameter name (data type): the format in which the description is to be written 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 = 0 # Initialization of input parameters 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. # The first line of the abbreviated function description # Blank line to align detailed description Extended description of function. # Align on a blank line, write the contents of each of the args, variable name (type): description Args: arg1 (int): Description of arg1 arg2 (str): Description of arg2 # Empty line alignment, different cases of if else Return value (type): description Returns: int/float/bool dtype: Description of return value """
Example
Finally complete the example of writing a class according to the style:
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: (str): dog name (str): dog family (int) : dog age gender(bool) : dog gender, male=1,famale=0 (float): dog weight size(str) : dog size """ = = = = # __legs(int) : dog legs, privite attribute, not the inputs params, written in front with # as a comment, not part of the initialization of the inputs params self.__legs = 4 """Write in triple quotes after__legs(int) : dog legs,privite attribute""" = size = 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') # Note: return can jump out of a function from any depth, None
Simple way to write Python classes
class MyClass: name = '' age = 0 __weight = 0 # Private variables def __init__(self, n, a, w): #self must be the first argument of the function = n = a self.__weight = w def speak(self): print('%says: I %s years old'%(, )) x = MyClass('yao', 10, 30) ()
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.