Home  >  Article  >  Backend Development  >  Introduction to static methods and dynamic methods in Python

Introduction to static methods and dynamic methods in Python

高洛峰
高洛峰Original
2017-03-26 18:46:422148browse

This article mainly provides you with an in-depth analysis of the relevant information on the introduction of static methods and dynamic methods in Python. It has certain reference value. Interested friends can refer to it

# -*- coding: utf-8 -*-
"""
Created on Sun Nov 13 23:19:03 2016
 
@author: toby
"""
#知识点:静态方法和动态方法
#静态方法属于类
#动态方法属于对象
 
class Province:
    memo = 'One of China\'s 23 provinces' #静态字段
     
    def __init__(self,name,capital,leadership):
        self.Name = name #动态字段
        self.Capital = capital #动态字段
        self.Leadership = leadership #动态字段
         
    def sports(self): #定义一个动态方法,类不能访问动态方法
        print self.Name + 'The sports meeting'
     
    #定义一个静态方法,实现类可以访问这个方法
    @staticmethod #第一步、加一个自带的装饰器
    def Foo(): #第二步,把shelf去掉
        print 'Anti-corruption activities'
 
#实例化两个对象,对象名分别是:hb、sd
hb = Province('hebei','shjiazhuang','liyang')
sd = Province('shandong','jinan','angshenghui')
 
#对象访问动态方法(注意:类不能访问动态方法)
hb.sports()
sd.sports()
 
#通过类名访问静态方法
Province.Foo()
 
#那么,对象是否能够访问静态方法呢?答案是可以的
hb.Foo()

The above is the detailed content of Introduction to static methods and dynamic methods in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn