Notes on Python Problems

  • Tags : python
  • time :

Question 1 TypeError: unbound method must be called with instance as first argument (got int instance read) in Python 2.

Solution:
1. Add @before the method; Staticmethod makes it a static method, one of its features is that parameters can be empty, and it also supports two calling methods: class name and object.

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. Add @before the method; Classmethod makes it a class method, and one characteristic of this type of method is that it can be called through the class name, but it must also pass a parameter. Generally, cls is used to represent class, which means that it can be directly called through the 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. Set the first parameter of the class method to self, making it accessible through instances of the class.

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) 

Question 2 : local variable 'x' referenced before assignment.

Solution:
1. Check if the prompted variable was called before assignment.

def fun1():
x = 5
def fun2():
  x *= 2
  return x
return fun2()
fun1()
 in this example, by http://pythontutor.com/visualize.html#mode=edit 
 observing the execution process, it is executed until fun 2 () x*= at 2 o'clock, an error message appears, that is fun 2 () x the multiplication operation was performed without being assigned an initial value. 
 because x yes fun the local variable in 1 () is denoted as x 1. in the fun 2 () x by fun the local variable of 2 () is denoted as x2,x 1. for fun 2 () is a non global external variable that exists in fun assignment pairs in 1 () fun 2 () does not take effect. 
 **solution** : apply nonlocal keyword 
def fun1():
x = 5
def fun2():
  nonlocal x
  x *= 2
  return x
return fun2()
fun1()
 okay, you're done with it nonlocal x afterwards, in the fun 2 () will no longer include x regarded as fun the internal variable of 2, fun in the 1 function, the x the definition will not be blocked. 

Question three : Function() takes exactly 2 arguments (3 given) [duplicate]
That is, the function requires two variables, but we have given three.

Solution: For functions declared in the class, set the first variable to self, so that when called, its first parameter matches.

def values_to_insert(self, a, b):

Question 4 How to construct a function that returns multiple values.

Solution: In order to return multiple values, the function simply returns a tuple.

>>> def myfun():.. return 1, 2, 3...
>>> a, b, c = myfun()
>>> a
1
>>> b
2
>>> c
3
>>> d = myfun()
>>> d
(1, 2, 3)
 when we call a function that returns a tuple, we usually assign the result to multiple variables, as shown above. actually, this is 1 . the tuple unpacking we mentioned in section 1. the return result can also be assigned to a single variable, and in this case, the value of the variable is the tuple returned by the function itself 

Question 5 Error: 'int' object is not callable
That is, when using an int value to call another object, and an error message XXX is not callable occurs, it is very likely that you are calling a variable or object that cannot be called, specifically in the wrong way you call functions or variables.

Solution: Check if the value is the same as the type set by oneself, and if an object instance is named after a regular variable, which cannot be used to complete operations such as calling object instances.

Question 6 Python end of statement expected, which appears during print.

Solution:

 stay python used in 3 print(x )replace print x

Question 7 IndentationError: expected an indented block.

Solution: Enable the tab key to display spaces in the IDE, and do not mix tabs and spaces.

Question 8 Python cannot write on a single line, resulting in multiple lines.

Solution: Two methods:
and ().

 add at the end of a line" ", which means adding spaces 
>>> a = 'abc' ... 'def'
>>> a
'abcdef'
>>> a = ('abc'.. 'def')
>>> a
'abcdef'

Question 9 IndentationError: independent does not match any outside indentation level.

Solution: Same as problem seven.

Question 10 When referencing a module, TypeError: 'module' object is not callable.

Solution: The module here can be understood as a file name, and the file name and class name can be different. There can be no class in the file, only functions.

The rules for referencing modules in Python are: import module and from module import.

The difference is that in the former, all imported things need to be qualified with module names when used, while in the latter, it is not necessary. That is, there can be multiple classes in a module. When importing a module only, the module needs to be added and the class needs to be specified before calling the function. From module import can import all classes or only one class, and the function can be called directly using the class name.

test class (file name: test):
class Person(object):
	def __init__(self,name,age):
		self.name = name
		self.age = age
	def getName(self):
		return self.name
 import module method 1 :
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()
 import module method 2 :
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()

Question 11 Swapping string and float types.

Solution.

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

Question 12 Python division preserves two decimal places.

Solution:

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

Question 13 How to determine whether a list contains a certain element in Python.

Solution: In Python, the in and not in keywords can be used to determine whether a list contains an element.

theList = ['a’,’b’,’c’] 
if 'a’ in theList: 
print 'a in the list’
if 'd’ not in theList: 
print 'd is not in the list’

Question 14 : SynthexError invalid token
Reason: There is a 0 before the number, which is 04,03. Therefore, modify it to 4,3.

reference
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.

Related articles