python标识静态方法_Python基于staticmethod装饰器标示静态方法

英文文档:

staticmethod(function)

Return a static method for function.

A static method does not receive an implicit first argument.

The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

标示方法为静态方法的装饰器

说明:

1. 类中普通的方法,实际上既可以被类直接调用也可以被类的实例对象调用,但是被实例对象调用的时候,要求方法至少有一个参数,而且调用时会将实例对象本身传给第一个参数

>>> class Student(object):

def __init__(self,name):

self.name = name

def sayHello(lang):

print(lang)

if lang == 'en':

print('Welcome!')

else:

print('你好!')

>>> Student.sayHello

>>> a = Student('Bob')

>>> a.sayHello

>

>>> Student.sayHello('en') # 类调用的时候,将'en'传给了lang参数

en

Welcome!

>>> a.sayHello() # 类实例对象调用的时候,将对象本身自动传给了lang参数,不能再接收参数

你好!

>>> a.sayHello('en')  Traceback (most recent call last):  File "", line 1, in   a.sayHello('en')  TypeError: sayHello() takes 1 positional argument but 2 were given

2. staticmethod函数功能就是将一个方法定义成类的静态方法,正确的方法是使用 @staticmethod装饰器,这样在实例对象调用的时候,不会把实例对象本身传入静态方法的第一个参数了。

# 使用装饰器定义静态方法

>>> class Student(object):

def __init__(self,name):

self.name = name

@staticmethod

def sayHello(lang):

print(lang)

if lang == 'en':

print('Welcome!')

else:

print('你好!')

>>> Student.sayHello('en') #类调用,'en'传给了lang参数

en

Welcome!

>>> b = Student('Kim') #类实例对象调用,不再将类实例对象传入静态方法

>>> b.sayHello()

Traceback (most recent call last):

File "", line 1, in

b.sayHello()

TypeError: sayHello() missing 1 required positional argument: 'lang'

>>> b.sayHello('zh') #类实例对象调用,'zh'传给了lang参数

zh

你好!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: Python基于staticmethod装饰器标示静态方法

本文地址: http://www.cppcns.com/jiaoben/python/355108.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值