python面试题之下面这些是什么意思:@classmethod, @staticmethod, @property?
回答背景知识
这些都是装饰器(decorator)。装饰器是一种特殊的函数,要么接受函数作为输入参数,并返回一个函数,要么接受一个类作为输入参数,并返回一个类。
@标记是语法糖(syntactic sugar),可以让你以简单易读得方式装饰目标对象。
@my_decorator
def my_func(stuff):
do_things
Is equivalent to def my_func(stuff):
do_things my_func = my_decorator(my_func)
你可以在本网站上找到介绍装饰器工作原理的教材。
真正的答案
@classmethod
, @staticmethod
和@property
这三个装饰器的使用对象是在类中定义的函数。下面的例子展示了它们的用法和行为:
class MyClass(object):
def __init__(self):
self._some_property = "properties are nice"
self._some_other_property = "VERY nice"
def normal_method(*args,**kwargs):
print "calling normal_method({0},{1})".format(args,kwargs)
@classmethod
def class_method(*args,**kwargs):
print "calling class_method({0},{1})".format(args,kwargs)
@staticmethod
def static_method(*args,**kwargs):
print "calling static_method({0},{1})".format(args,kwargs)
@property
def some_property(self,*args,**kwargs):
print "calling some_property getter({0},{1},{2})".format(self,args,kwargs)
return self._some_property
@some_property.setter
def some_property(self,*args,**kwargs):
print "calling some_property setter({0},{1},{2})".format(self,args,kwargs)
self._some_property = args[0]
@property
def some_other_property(self,*args,**kwargs):
print "calling some_other_property getter({0},{1},{2})".format(self,args,kwargs)
return self._some_other_property o = MyClass()
# 未装饰的方法还是正常的行为方式,需要当前的类实例(self)作为第一个参数。 o.normal_method
# <bound method MyClass.normal_method of <__main__.MyClass instance at 0x7fdd2537ea28>> o.normal_method()
# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>,),{}) o.normal_method(1,2,x=3,y=4)
# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>, 1, 2),{'y': 4, 'x': 3}) # 类方法的第一个参数永远是该类 o.class_method
# <bound method classobj.class_method of <class __main__.MyClass at 0x7fdd2536a390>> o.class_method()
# class_method((<class __main__.MyClass at 0x7fdd2536a390>,),{}) o.class_method(1,2,x=3,y=4)
# class_method((<class __main__.MyClass at 0x7fdd2536a390>, 1, 2),{'y': 4, 'x': 3}) # 静态方法(static method)中除了你调用时传入的参数以外,没有其他的参数。 o.static_method
# <function static_method at 0x7fdd25375848> o.static_method()
# static_method((),{}) o.static_method(1,2,x=3,y=4)
# static_method((1, 2),{'y': 4, 'x': 3}) # @property是实现getter和setter方法的一种方式。直接调用它们是错误的。
# “只读”属性可以通过只定义getter方法,不定义setter方法实现。 o.some_property
# 调用some_property的getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# 'properties are nice'
# “属性”是很好的功能 o.some_property()
# calling some_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'str' object is not callable o.some_other_property
# calling some_other_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# 'VERY nice' # o.some_other_property()
# calling some_other_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'str' object is not callable o.some_property = "groovy"
# calling some_property setter(<__main__.MyClass object at 0x7fb2b7077890>,('groovy',),{}) o.some_property
# calling some_property getter(<__main__.MyClass object at 0x7fb2b7077890>,(),{})
# 'groovy' o.some_other_property = "very groovy"
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: can't set attribute o.some_other_property
# calling some_other_property getter(<__main__.MyClass object at 0x7fb2b7077890>,(),{})
本文首发于Python黑洞网,博客园同步跟新
python面试题之下面这些是什么意思:@classmethod, @staticmethod, @property?的更多相关文章
- Python类中装饰器classmethod,staticmethod,property,
@classmethod 有的时候在类中会有一种情况,就是这个方法并不需要使用每一个对象属性 因此 这个方法中的self参数一个完全无用的参数,使用classmethod class A: __cou ...
- 最新Python笔试题2017 涵盖知识面广泛
引言 想找一份Python开发工作吗?那你很可能得证明自己知道如何使用Python.下面这些问题涉及了与Python相关的许多技能,问题的关注点主要是语言本身,不是某个特定的包或模块.每一个问题都可以 ...
- 转--python 面试题
# 每一题都值得好好琢磨钻透 [原文地址](http://www.cnblogs.com/Allen-rg/p/7693394.html)1.Python是如何进行内存管理的? 答:从三个方面来说,一 ...
- Python面试题 —— 获取列表中位数
中位数是一个可将数值集合划分为相等的上下两部分的一个数值.如果列表数据的个数是奇数,则列表中间那个数据就是列表数据的中位数:如果列表数据的个数是偶数,则列表中间那2个数据的算术平均值就是列表数据的中位 ...
- python公司面试题集锦 python面试题大全
问题一:以下的代码的输出将是什么? 说出你的答案并解释. class Parent(object): x = 1 class Child1(Parent): pass class Child2(Par ...
- 【Python】【面试必看】Python笔试题
前言 现在面试测试岗位,一般会要求熟悉一门语言(python/java),为了考验求职者的基本功,一般会出 2 个笔试题,这些题目一般不难,主要考察基本功.要是给你一台电脑,在编辑器里面边写边调试,没 ...
- Python面试题整理-更新中
几个链接: 编程零基础应当如何开始学习 Python ? - 路人甲的回答 网易云课堂上有哪些值得推荐的 Python 教程? - 路人甲的回答 怎么用最短时间高效而踏实地学习 Python? - 路 ...
- python 面试题4
Python面试题 基础篇 分类: Python2014-08-08 13:15 2071人阅读 评论(0) 收藏 举报 最近,整理了一些python常见的面试题目,语言是一种工具,但是多角度的了解工 ...
- 一道Python面试题
无意间,看到这么一道Python面试题:以下代码将输出什么? def testFun(): temp = [lambda x : i*x for i in range(4)] return ...
随机推荐
- fiddler 暂停抓包
或者点击左下角 capturing
- 为什么tcp-wrappers被Redhat Centos Fedora废弃?
1 简述 TCP wrappers is a simple tool to block incoming connection on application level. This was very ...
- FTP上传下载文件(函数简易版)
FTP上传下载文件(函数简易版) # 服务端 import socket import json import hashlib import struct import os user_dic = { ...
- java并发编程之美-阅读记录1
1.1什么是线程? 在理解线程之前先要明白什么是进程,因为线程是进程中的一个实体.(线程是不会独立存在的) 进程:是代码在数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,线程则是进程中的 ...
- C#反射的实现
一,什么是反射? 1,System.Reflection 命名空间中的类与 System.Type 使你能够获取有关加载的程序集和其中定义的类型的信息,如类.接口和值类型. 可以使用反射在运行时创建. ...
- 【记录】elasticsearch 注解
先记录地址,之后再整理 参考地址:https://blog.csdn.net/qq_28364999/article/details/81109666 https://blog.csdn.net/dy ...
- mybatis 自定义查询语句
通过mybatis插件生成的mapper文件只有基本的增.删.改.查.汇总.但是实际使用场景中,总是有各种需要连表.汇总.分组查询的需求,那我们一般都通过自定义查询语句去实现. 有时候会有表结构更改的 ...
- 笔记73 高级SSM整合2
遇到的问题: 1.表单信息校验:jQuery前端校验,ajax用户名重复校验,重要信息后端校验(JSR303)+数据库约束 2.在设置下拉列表显示的值时出现问题. 3.邮箱也添加重复性校验 4.pub ...
- css3--css3模块
CSS3被拆分为"模块".旧规范已拆分成小块,还增加了新的. 一些最重要CSS3模块如下: 1.选择器(.基本选择器,层次选择器,伪类选择器,伪元素,属性选择器,通配符) 2.盒模 ...
- 横纵方向走马灯滚动,纯javascript代码
<body onload="beginmarquee()"> <table width="1024" border="0" ...