Python 问题小记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014001964/article/details/82262292

问题一:TypeError: unbound method must be called with instance as first argument (got int instance instead) in Python 2
即:方法调用时没有对类进行实例化,类比到java中,类中的方法调用前,没有new对象

解决方案:
1.方法前加 @staticmethod 使其成为静态方法,他的一个特点是参数可以为空,同样支持类名和对象两种调用方式

class calc:

    @staticmethod
    def add(x,y):
        answer = x + y
        print(answer)

#call staticmethod add directly 
#without declaring instance and accessing class variables
calc.add(5,7)

2.方法前加 @classmethod 使其成为类方法,这种类方法的一个特点就是可以通过类名去调用,但是也必须传递一个参数,一般用cls表示class,表示可以通过类直接调用

class calc:

    some_val = 1

    @classmethod
    def add_plus_one(cls,x,y):
        answer = x + y + cls.some_val #access class variable
        print(answer)

#call classmethod add_plus_one dircetly
#without declaring instance but accessing class variables
calc.add_plus_one(5,7)

3.类方法第一个参数设置为self,使其可通过类的实例去访问

class calc:

    def add(self,x,y):
        print(self._add(x,y)) #call another instance method _add
    def _add(self,x,y):
        return x+y

#declare instance
c = calc()
#call instance method add
c.add(5,7) 

问题二:local variable ‘x’ referenced before assignment
即:在赋值前引用局部变量x

解决方案:
1.检查提示的变量,是否在赋值前便被调用了

def fun1():
    x = 5
    def fun2():
        x *= 2
        return x
    return fun2()
fun1()

这个例子中,通过http://pythontutor.com/visualize.html#mode=edit 
观察执行流程,其执行到 fun2()的 x*=2时提示出错误,即fun2()中的 x 并没有被赋初值,便执行了乘法的操作。
因为x是fun1()中的局部变量,记为x1,在fun2()中的x为fun2()的局部变量,记为x2,x1对于fun2()为非全局的外部变量,其在fun1()中的赋值对fun2()并不生效。

**解决办法**:使用nonlocal关键字
def fun1():
    x = 5
    def fun2():
        nonlocal x
        x *= 2
        return x
    return fun2()

fun1()
即可,使用了nonlocal x后,在fun2()中就不再将x视为fun2的内部变量,fun1函数中对x的定义就不会被屏蔽掉。

问题三:Function() takes exactly 2 arguments (3 given) [duplicate]
即:函数需要两个变量,但我们给了3个

解决方案:
在类里声明的函数,将首个变量设置为self,这样在调用的时候,其第一个参数就匹配上了

def values_to_insert(self, a, b):

问题四:如何构造一个返回多个值的函数

解决方案:为了能返回多个值,函数直接return一个元组就行了

>>> def myfun():
... return 1, 2, 3
...
>>> a, b, c = myfun()
>>> a
1
>>> b
2
>>> c
3
>>> d = myfun()
>>> d
(1, 2, 3)

当我们调用返回一个元组的函数的时候 ,通常我们会将结果赋值给多个变量,就像上面的那样。 其实这就是1.1小节中我们所说的元组解包。返回结果也可以赋值给单个变量, 这时候这个变量值就是函数返回的那个元组本身了

问题五:Error:’int’ object is not callable
即:使用一个int值去调用别的对象,当出现报错 XXX is not callable的时候,很有可能是你正在调用一个不能被调用的变量或对象,具体表现就是你调用函数、变量的方式错误。

解决方案:检查该值是否与自己设置的类型相同,是否将一个对象实例与一个普通变量同名,其不能在完成对象实例的调用等操作

问题六:python end of statement expected,其在print 时出现

解决方案:

在python3中使用 print(x) 代替 print x

问题七:IndentationError:expected an indented block

解决方案:开启ide的空格即tab键显示,不要tab 和空格混用

问题八:python一行写不下,变多行

解决方案:
\和() 两种方法

在一行末尾 加上“ \”,也就是空格加上\
>>> a = 'abc' \
... 'def'
>>> a
'abcdef'
>>> a = ('abc'
... 'def')
>>> a
'abcdef'

问题九:IndentationError:unindent does not match any outer indentation level

解决方案:同问题七

问题十:引用模块时,TypeError: ‘module’ object is not callable

解决方案:这里的模块可以理解为文件名,文件名和类名可以不一致,文件中可以没有类,只有函数

python 引用模块的规则是:import module 和 from module import

区别是前者所有导入的东西使用时需加上模块名的限定,而后者则不需要,即一个module里可以有多个类,仅import module时, 调用需要将module加上,并指定类,再去调用函数,from module import 可以 import 所有的类,也可以只import 一个类,此时可以直接使用类名调用函数

test类(文件名为test):
class Person(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def getName(self):
        return self.name

导入模块方式一:
import test
class Nancy(object):
    def __init__(self):
        pass

    def getNancyName(self):
        nancy = test.Person("xiaoxi",18)
        print nancy.getName()

if __name__ == '__main__':
    nancy = Nancy()
    nancy.getNancyName()

导入模块方式二:
from test import Person 

class Nancy(object):
    def __init__(self):
        pass

    def getNancyName(self):
        nancy = Person("xiaoxi",18)
        print nancy.getName()

if __name__ == '__main__':
    nancy = Nancy()
    nancy.getNancyName()

问题十一:string 与float 类型互换

解决方案

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

问题十二:python除法保留两位小数

解决方案:

float('%.2f'%(10.0/3.0))

问题十三:python 中如何判断list中是否包含某个元素

解决方案:在python中可以通过in和not in关键字来判读一个list中是否包含一个元素

theList = [‘a’,’b’,’c’] 
ifain theList: 
    print ‘a in the list’

if ‘d’ not in theList: 
    print ‘d is not in the list’

参考
1.https://stackoverflow.com/questions/40701142/typeerror-unbound-method-must-be-called-with-instance-as-first-argument-got-in/40701173
2.https://www.cnblogs.com/dcb3688/p/4260732.html
3.https://blog.csdn.net/zhuzuwei/article/details/78234748

猜你喜欢

转载自blog.csdn.net/u014001964/article/details/82262292
今日推荐