Tag Archives: Python

[design and development] Python learning notes – Super () argument 1 must be type, not classobj

 1 #!/usr/bin/python
 2 # -*- coding:UTF-8 -*-
 3 
 4 class Person():
 5   "A Person class"
 6 
 7   def __init__(self,name,age):
 8     self.name =name
 9     self.__age = age
10 
11   def Introduce(self):
12     print "Hi, My name is:%s,I'm %d years-old."%(self.name,self.__age)
13 
14 
15 class Student(Person):
16   "A student class <- Person"
17 
18   def __init__(self,name,age,score):
19     Person.__init__(self,name,age)  #Notice:If don't call person.__init__ then Student class will lose name and age.
20     self.score = score
21   
22   def ReportScore(self):
23     super(Student,self).Introduce()
24     print "My score is:%d"%(self.score)
25 
26   def __str__(self):
27     return "This is a student class"
28 
29 
30 s1=Student('A',20,80)
31 
32 #s1.Introduce()
33 s1.ReportScore()

Error on line 23 of the above code:

➜  Python git:(master) ✗ python oop_syntax.py
Traceback (most recent call last):
  File "oop_syntax.py", line 33, in <module>
    s1.ReportScore()
  File "oop_syntax.py", line 23, in ReportScore
    super(Student,self).Introduce()
TypeError: super() argument 1 must be type, not classobj

Reference practice: https://blog.csdn.net/andos/article/details/8973368

Change person to a new class to solve the problem

 1 #!/usr/bin/python
 2 # -*- coding:UTF-8 -*-
 3 
 4 class Person(object):
 5   "A Person class"
 6 
 7   def __init__(self,name,age):
 8     self.name =name
 9     self.__age = age
10 
11   def Introduce(self):
12     print "Hi, My name is:%s,I'm %d years-old."%(self.name,self.__age)

Fast locating nonetype ‘object is not Iterable in Python

One word solution

There are two ways to solve such problems

1. Check whether the list in all for loops has none

2. Check all scenarios that call function to return multiple parameters, check whether there are branches inside the function, and whether each branch has a return value

Verification

# coding: utf-8
value = 0

def test():
    if value == 1:
        a = b = 1
        return a, b

def case1():
    a, b = test()
    print a

def case2():
    items = None
    for item in items:
        print item

if __name__ == '__main__':
    print case2()



Error information:

TypeError: ‘NoneType’ object is not iterable

Summary

The most common error scenario of ‘nonetype’ object is not Iterable is that the list in the for loop is none

When assigning none to multiple values, a prompt will also appear: typeerror: ‘nonetype’ object is not Iterable

Function return value must consider the coverage of conditional branch

When there is no return statement, python returns none by default

Case 1 is easy to ignore

therefore, if this error occurs, we should check from the above two scenarios, such as whether there is a value of none used in the loop, whether the called function has branches, and whether each branch has a return value

Reference

https://www.cnblogs.com/zhaijiahui/p/8391701.html

TypeError: not enough arguments for format string

solve python

for i in range(1,10):

​    for j in range(1,i+1):

​        s = i*j

​        print('%d*%d='%i,j,s,end="\t") 

​    print("\t")

Type error: not enough arguments for format string

Once the parameters are enclosed in brackets (as shown below), the problem is solved

        print('%d*%d='%(i,j),s,end="\t") 

Summary

When there are multiple formatted outputs, the parameters after% should be enclosed in brackets

​ print(“%s : %s “%(x,y))

Go to: install C extended compiler environment of Python under windows (solve the problem of “unable to find vcfarsall. Bat”

Individual articles are original or translated unless reprinted

Individual articles are welcome to be reprinted in various forms, but those over 18 years old are requested to indicate the source of the article, respect my labor and your intelligence

Link to this article: http://www.cnblogs.com/fbwfbi/p/4509622.html

N hasn’t started blogging for a long time. I always feel that I need to remember something casually. I’ve lost some things, technologies and tools. I’d better record every bit of them

In windows, PIP is used to install some third-party libraries of Python. Many of them use C to write some extensions and need to use VC + + compiler to compile and install (or use MinGW, generally not recommended). Otherwise, it will appear “ unable to find vcfarsall. Bat “. For example, python 2.7 needs to use VS2008 C + + compiler, while python3 to python3.4 (python3.5 will use vs2015) will use VS2010 to compile. However, anyone who has ever installed vs, a huge and bloated IDE, knows that it comes with a lot of Microsoft plug-ins that you don’t know whether they are useful or not. They occupy a lot of space on C disk and start slowly, although the interface function of IDE is barely passable. If the computer configuration is general, this thing will make n cards, generally do not do related development, there is no need to install the entire vs. For Python 2.7, Microsoft has a conscience. It directly launched Microsoft Visual C + + compiler for Python 2.7, which can be downloaded and installed directly. Then, in the start menu – “all programs”, find the corresponding directory, and according to your platform and python Version (select x86 or x64), click the corresponding command prompt to run. In this CMD window, you can enter the set command to check the environment variables. It is found that the parameters include =, path =, lib =, and libpath = have been set, so you can enter them directly

pip install numpy

You can install and compile the corresponding third-party modules and libraries. Sometimes the compilation process is long and you need to wait patiently

But for Python 3, it’s not so convenient. Because my Python 3.4 is 64 bit, it’s obviously impossible to use VS2010 express directly, because it only has x86 version by default, not 64 bit. Refer to a question and answer in stack overflow

Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

According to the above suggestions, I get the corresponding solution on this machine. First install VS2010 express, then install windows SDK 7.1, and finally install a 64 bit compiler patch

  Microsoft SDK 7.1 (Windows 7)

  VC-Compiler-KB2519277

PS: before installing SDK 7.1, please uninstall VC redistribute 2010 related component packages (including x86 and x64), otherwise an error will be reported

After completing the above steps, the basic MSVC compilation environment (including x64) has been configured. However, if you compile a project in the future, such as building a Qt5 project, the following errors will appear:

c:\program files (x86)\microsoft visual studio 10.0\vc\include\intrin.h(26):fatal error C1083: Cannot open include file: ‘ammintrin.h’: No such file or directory

At this time, you can download the corresponding ammintrin. H from the Internet, and put it in the directory of C:// program files (x86) \ \ Microsoft Visual Studio 10.0 \ \ VC \ \ include \, which can be downloaded from the following Baidu Library:

ammintrin. H header file, which is required after installing kb2519277 patch in Windows SDK 7.1

After installation, in the start menu, find “windows SDK 7.1 command prompt”, click Run, and set the corresponding compilation environment through setenv in the shell, as shown in the following figure:

After setting “setenv/x64”, you can install the corresponding package in the 64 bit compiling environment

At this point, you may need to mention that after setting up the environment, you can install numpy in Python 2.7 and python 3.4 respectively. You find that py2 is OK, but PY3 fails to install and compile link (you have tested it in the virtual machine before, but PY3 installation is OK). Why?Please compare the following two pictures:

Obviously, when py2 is installed, libpath under the link command line uses “” to cause it. Therefore, the path with spaces will not partition the parameters. PY3 is not so detailed. I don’t know whether it is the fault of PIP and setuptools calling the CMD command or the bug in distutils. Anyway, the installation path of PY3 can’t have spaces. So I adjusted the installation path of python3, that is, there is no space, and the compilation is successful

Of course, this is just a VC + + compilation environment. For a numerical calculation library like SciPy, you need a FORTRAN compiler to install it. Obviously, the compilation and installation under windows is far less convenient than that under Linux (except that the package name is not easy to remember and the package dependence is troublesome). GCC and gfortran are ready-made, and apt get is also ready-made. Therefore, if you develop and test under windows, you can directly use a large number of compiled and packaged windows wheel installation packages provided by the University of California, Irvine (UCI), which contain numpy, SciPy, Matplotlib and other module libraries for numerical analysis and scientific calculation, and all of them are MKL versions. Download the corresponding version and directly use “PIP install XXX. WHL” to complete the installation. The WHL file is just like a zip file. You can also use the compression software to unpack it and put it in the corresponding lib/site packages directory. Of course, you can also use the python customized environment version Anaconda , which has directly integrated the above packages, including the easy-to-use repl tool like IPython and CONDA package management

The solution to the problem of unified does not match any outer indentation level in pychar platform

Python has strict requirements for indentation

If you pay attention to it a little bit, you will get the error of unified does not match any outer indentation level


1. The indent before and after the code is inconsistent

You can see that there is a small red wavy line in front of def, which indicates that there is an indentation error here. Obviously, the indentation of the annotation in front of DEF is inconsistent with that of def (one is 2 and the other is 4). Just change it to be consistent

2. The indent before and after the code is inconsistent

In the figure above, the indent in front of the definitions of the two functions are the same, but an error prompt appears after x = 3, which indicates that an indent error has occurred near the sentence (before and after). Move the mouse to the highlighted yellow area or the red wavy line error area, and the error message will be displayed

From the error message, we can see that x = 3 does not match the following indentation. Further, we can see the prompt in the second figure: discontinuous indentation, tab indentation in the previous line, and sapce indentation in this line. Obviously, it is OK to change the indentation in front of def test2 to tab

Also, change the indentation before y = 3

3. Mixing tab and space

Obviously, if you use space and tab to indent in front of a piece of code, an error will naturally occur. At this time, pychar will automatically judge and adjust according to your preset indentation value

The indentation value you set is set in the settings above, which is generally 4, and the figure above is 3

If you open someone else’s Python program or Python script, it is very likely that there will be an indentation error. At this time, you only need to modify the indentation amount of the error place. Or use global substitution to replace spaces and indents in your code

Use the shortcut key of crtl + H to replace

In the figure above, replace tab (\ T) with four spaces. Note that you need to check the regex option when replacing symbols. The green area in the figure is tab area, and the yellow area is space area

undertake MATLAB, Python and C + + programming, machine learning, computer vision theory implementation and guidance, undergraduate and master can, please contact QQ 757160542 for details

This article shares in the blog “Yu Xiaoyong” (CSDN).

Python: How to Read file initialization from file failed by panda

Pandas reports the following error when reading the file:

--------------------------------------------------------------------------
OSError                                  Traceback (most recent call last)
<ipython-input-21-f8680ec116e3> in <module>()
      1 #f = open(path)
----> 2 res = pd.read_csv('myfile.csv')

E:\anaconda_python\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    644                     skip_blank_lines=skip_blank_lines)
    645 
--> 646         return _read(filepath_or_buffer, kwds)
    647 
    648     parser_f.__name__ = name

E:\anaconda_python\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
    387 
    388     # Create the parser.
--> 389     parser = TextFileReader(filepath_or_buffer, **kwds)
    390 
    391     if (nrows is not None) and (chunksize is not None):

E:\anaconda_python\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds)
    728             self.options['has_index_names'] = kwds['has_index_names']
    729 
--> 730         self._make_engine(self.engine)
    731 
    732     def close(self):

E:\anaconda_python\lib\site-packages\pandas\io\parsers.py in _make_engine(self, engine)
    921     def _make_engine(self, engine='c'):
    922         if engine == 'c':
--> 923             self._engine = CParserWrapper(self.f, **self.options)
    924         else:
    925             if engine == 'python':

E:\anaconda_python\lib\site-packages\pandas\io\parsers.py in __init__(self, src, **kwds)
   1388         kwds['allow_leading_cols'] = self.index_col is not False
   1389 
-> 1390         self._reader = _parser.TextReader(src, **kwds)
   1391 
   1392         # XXX

pandas\parser.pyx in pandas.parser.TextReader.__cinit__ (pandas\parser.c:4184)()

pandas\parser.pyx in pandas.parser.TextReader._setup_parser_source (pandas\parser.c:8471)()

OSError: Initializing from file failed

When you use panda to read a file and report this error, it is usually because your file name contains Chinese, for example:

res = pd.read_csv('myfile.csv')

In this case, an error will be reported

f = open('myfile.csv')
res = pd.read_csv(f)

Then you can read the file

Pyenv build failed solution

Today, I have a headache caused by the Chinese problem of python2. X. I found that python3. X supports Chinese very well, but I am worried that some packages do not support the version of python3. We use pyenv to manage python.

Operating system: OSX 10.11

First of all, I used homebrew to install pyenv. In this step, I saw some mistakes on the Internet, and then how to solve them. Fortunately, I didn’t make any mistakes here. I thought it would be over. Here’s the problem

Problem: when using pyenv install 3.4.1, the following problems occurred after downloading

Downloading Python-3.4.1.tgz...-https://yyuu.github.io/pythons/44a3c1ef1c7ca3e4fd25242af80ed72da941203cb4ed1a8c1b724d9078965dd8
Installing Python-3.4.1...

BUILD FAILED (OS X 10.9.5 using python-build 20150124)

Inspect or clean up the working tree at /var/folders/zf/1b6kcyd53hg0crv65j108_7m0000gn/T/python-build.20150127150918.87726
Results logged to /var/folders/zf/1b6kcyd53hg0crv65j108_7m0000gn/T/python-build.20150127150918.87726.log

Last 10 log lines:
  File "/private/var/folders/zf/1b6kcyd53hg0crv65j108_7m0000gn/T/python-build.20150127150918.87726/Python-3.4.1/Lib/ensurepip/__main__.py", line 4, in <module>
    ensurepip._main()
  File "/private/var/folders/zf/1b6kcyd53hg0crv65j108_7m0000gn/T/python-build.20150127150918.87726/Python-3.4.1/Lib/ensurepip/__init__.py", line 209, in _main
    default_pip=args.default_pip,
  File "/private/var/folders/zf/1b6kcyd53hg0crv65j108_7m0000gn/T/python-build.20150127150918.87726/Python-3.4.1/Lib/ensurepip/__init__.py", line 116, in bootstrap
    _run_pip(args + [p[0] for p in _PROJECTS], additional_paths)
  File "/private/var/folders/zf/1b6kcyd53hg0crv65j108_7m0000gn/T/python-build.20150127150918.87726/Python-3.4.1/Lib/ensurepip/__init__.py", line 40, in _run_pip
    import pip
zipimport.ZipImportError: can't decompress data; zlib not available
make: *** [install] Error 1

Solution: use the following statement to install to solve the problem

CFLAGS="-I$(xcrun --show-sdk-path)/usr/include" pyenv install -v 3.4.1

reason:

zipimport.ZipImportError: can't decompress data; zlib not available

So far, the installation of the new version of Python is complete. You can use pyenv versions to view the installation results( The asterisk here should be on the system. I have modified the python version.)

 system
* 3.4.1 (set by /usr/local/var/pyenv/version)

In addition, warm reminder, after using homebrew to install pyenv, the prompt to install homebrew is in. Bash_ I don’t know if it has anything to do with the order. I can’t change the version of Python after adding it backwards.

You can use brew info pyenv to view these two sentences.
the results are as follows:

pyenv: stable 20160310, HEAD
Python version management
https://github.com/yyuu/pyenv
/usr/local/Cellar/pyenv/20160310 (473 files, 2.1M) *
  Built from source
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/pyenv.rb
==> Dependencies
Recommended: autoconf ✔, pkg-config ✔, openssl ✔, readline ✔
==> Options
--without-autoconf
    Build without autoconf support
--without-openssl
    Build without openssl support
--without-pkg-config
    Build without pkg-config support
--without-readline
    Build without readline support
--HEAD
    Install HEAD version
==> Caveats
To use Homebrew's directories rather than ~/.pyenv add to your profile:
  export PYENV_ROOT=/usr/local/var/pyenv

To enable shims and autocompletion add to your profile:
  if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi

That is to add the following two sentences:

To use Homebrew's directories rather than ~/.pyenv add to your profile:
  export PYENV_ROOT=/usr/local/var/pyenv

To enable shims and autocompletion add to your profile:
  if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi

At this point, you can successfully switch the python version by using pyenv global 3.4.1 .

Importerror: DLL load failed: the specified module was not found. Solution

Importerror: DLL load failed: the specified module was not found. Solution

After the coolprop is successfully installed, pychar reports an error when importing coolprop: importerror: DLL load failed: the specified module cannot be found.

After two days of investigation, I didn’t know where the problem was, and finally solved it according to the blogger’s method.

Link:[ https://blog.csdn.net/weixin_ 44663675/article/details/91957566?utm_ medium=distribute.pc_ relevant.none-task-blog-BlogCommendFromMachineLearnPai2-12.nonecase& depth_ 1-utm_ source=distribute.pc_ relevant.none-task-blog-BlogCommendFromMachineLearnPai2-12.nonecase]

Personally, the problem is that visual c + + is not installed. Coolprop should rely on Visual C + +, which is the same as tensorflow<
link:
[ https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads ]
download and install the required version of Visual C + + in the link above, and the problem will be solved immediately.