python static class_Python staticmethod classmethed

Python中的staticmethod和classmethed作用类似于java中的static方法,但是在Python中这两种方法都可以被实例化的对象调用(不推荐这样使用)。

classmethed的参数列表中比staticmethod多一个cls,即类对象,Python中一个类也是一个实际存在的对象,所以可以在classmethed中使用cls继续调用staticmethod方法。

代码示例:

# !/usr/bin/env python

# -*- coding: utf-8 -*-

# author: 'zhonghua'

# filename: 'hello_world'

# create: '2016/3/27'

# version: 1.0

class HelloWorld:

def __init__(self):

print 'Init HelloWorld.'

@staticmethod

def hello_static(name):

print 'hello_static(): Hello %s' %name

print

@classmethod

def hello_class(cls, name):

print 'hello_class(): Hello %s' %name

print 'Now call hello_static():'

cls.hello_static(name)

print

def hello_world(self, name):

print 'hello_world(): Hello %s' %name

print

if __name__ == '__main__':

HelloWorld.hello_static('static')

HelloWorld.hello_class('class')

hw = HelloWorld()

hw.hello_world('common')

hw.hello_static('hw.static')

hw.hello_class('hw.class')

输出:

hello_static(): Hello static

hello_class(): Hello class

Now call hello_static():

hello_static(): Hello class

Init HelloWorld.

hello_world(): Hello common

hello_static(): Hello hw.static

hello_class(): Hello hw.class

Now call hello_static():

hello_static(): Hello hw.class

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值