这是我实际问题的简化示例.
我有一个这样foo定义的类foo.py:
class foo(object):
def __init__(self):
pass
def bar(self):
return True
@property
def baz(self):
return False
Run Code Online (Sandbox Code Playgroud)
现在,我想使用该inspect模块来获取foo类的方法(包括baz).这是我到目前为止所做的getmethods.py:
import foo
import inspect
classes = inspect.getmembers(foo, inspect.isclass)
for cls in classes:
methods = inspect.getmembers(cls[1], inspect.ismethod)
print methods
Run Code Online (Sandbox Code Playgroud)
当我运行此脚本时,我得到以下输出(这并非完全出乎意料):
[('__init__', <unbound method foo.__init__>), ('bar', <unbound method foo.bar>)]
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是,为什么baz不被认为是一种方法,我如何修改getmethods.py以获得以下输出:
[('__init__', <unbound method foo.__init__>), ('bar', <unbound method foo.bar>), ('baz', <property object at 0x7fbc1a73d260>)]
Run Code Online (Sandbox Code Playgroud) 在Python 2.7中,我得到以下结果:
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, file))
...
True
Run Code Online (Sandbox Code Playgroud)
在python 3.5中我得到:
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, file))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'file' is not defined
Run Code Online (Sandbox Code Playgroud)
因此,好的,我看一下Python文档,发现在Python 3.5中文件是类型io.IOBase(或某些子类)的。导致我这一点:
>>> import io
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, io.IOBase))
...
True
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用Python 2.7时:
>>> import io
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, io.IOBase))
...
False
Run Code Online (Sandbox Code Playgroud)
所以在这一点上,我很困惑。看着文档,我觉得Python 2.7应该报告 …
我在Python 3中计算一个人的BMI,需要检查BMI是否介于两个值之间.
这是我的代码:
def metricBMI():
text = str('placeholder')
#Get height and weight values
height = float(input('Please enter your height in meters: '))
weight = float(input('Please enter your weight in kilograms: '))
#Square the height value
heightSquared = (height * height)
#Calculate BMI
bmi = weight / heightSquared
#Print BMI value
print ('Your BMI value is ' + str(bmi))
if bmi < 18:
text = 'Underweight'
elif 24 >= bmi and bmi >= 18:
text = 'Ideal'
elif 29 >= bmi …Run Code Online (Sandbox Code Playgroud)